MangoDB CRUD Operations



What is CRUD ?

We are frequently heard about CRUD functions in the IT world. CRUD is nothing but a small thing simultaneously with significant functionality in the application.CRUD is the acronym for Create, Read, Update and Delete.












Create: This operation needs to insert one document in the database 

Read: This operation fetches the data from the database.

Update: This operation changes the value or changes the data from the database.

Delete: This operation removes data from the database.

How to work CRUD operations in MongoDB?

Now, Need to connect with your MongoDB database.

Create Operations:


CRUD operation has C means Creating one or more data in the database.
Mango DB have two functions for inserting table one is a single insert and the other is a multiple insert.

1.insertOne()     ---> To insert the single data.
2.insertMany() ---> To insert the multiple data.

insertOne() :

The insertOne() command allows to insert of one data into the collection.It have take some JSON type key/value pairs.

For this example, we have a collection whose collection name is the user. We can insert single data into the user collection through the insertOne() method.

execute the following commands:

db.user.insertOne({
name : "robbert",
age: 25,
gender:"male"
});

If the insert method did we have got a unique object id for the user.

db.user.insertOne({
name : "robbert",
age: 25,
gender:"male"
})

{ "acknowledged : true, "insertedId" : ObjectId("5fd989674e6b9ceb8665c57d") }

insertMany():

Inserting many documents to insert multiple data into the collection. We need to use the square brackets when inserting data. following commands:
db.user.insertMany(
[
{
name : "robbert",
age: 25,
gender:"male"
},
{
name : "thomas",
age: 35,
gender:"male"
}
]
)

Output look like this


db.user.insertMany(
[
{
name : "robbert",
age: 25,
gender:"male"
},
{
name : "thomas",
age: 35,
gender:"male"
}
]
)
{ "acknowledged" : true, "insertedIds" :                         [ ObjectId("5fd98ea9ce6e8850d88270b4"), ObjectId("5fd98ea9ce6e8850d88270b5")                           ] }

Read Operations: Read operation is retrieving the document from the collection. Read operations have two methods. 1)find() 2)findOne() find(): The method will return everything from a collection if you call without a parameter. following the example here is an example of getting data from the user collection:

db.user.find()

output will be like this: { "_id" : ObjectId("1"), "name" : "Robbert", "age" : "25","gender":"male" } { "_id" : ObjectId("2"), "name" : "Thomas", "age" : "25","gender":"male" } findOne():
The findOne() method will return only one data from the collection it depends on the criteria.
following the example: db.user.findOne({"name":"robbert"}) output will be like this: { "_id" : ObjectId("1"), "name" : "Robbert", "age" : "25","gender":"male" } Update Operation: The update operation is nothing but you change the value into the collection. When you update carefully because once we update we can't rollback. mangobd have three different methods 1)updateOne() 2)updateMany() 3)replaceOne() updateOne(): The updateOne method update the existing value. We can update only one value into the collection. We can pass two parameters one which collection we need to change and another one is "$set" to set the which value we need to change. following the example: db.users.updateOne({age:25},{$set{"name":'Rahul'}}) updateMany(): The updateMany() method using to update bulk data in the document based on given query. Example of updateMany() method, we have the book collection like { "_id" : ObjectId("6107b8caebc5f5d5e5e5d5a1"), "title" : "The Great Gatsby", "author" : "F. Scott Fitzgerald", "price" : 20 } { "_id" : ObjectId("6107b8caebc5f5d5e5e5d5a2"), "title" : "To Kill a Mockingbird", "author" : "Harper Lee", "price" : 18 } { "_id" : ObjectId("6107b8caebc5f5d5e5e5d5a3"), "title" : "1984", "author" : "George Orwell", "price" : 15 } { "_id" : ObjectId("6107b8caebc5f5d5e5e5d5a4"), "title" : "The Catcher in the Rye", "author" : "J.D. Salinger", "price" : 22 }

Now, we need increase 5 rupees in every book. you can use updateMany with $inc operator.
db.books.updateMany({}, { $inc: { price: 5 } })

This command will update all documents in the books collection by adding 5 to the price field. The first parameter {} is an empty query object that matches all documents in the collection. The second parameter { $inc: { price: 5 } } is the update operation that increments the price field by 5 for all matched documents.


After running the above command, the updated documents will look like this:

{ "_id" : ObjectId("6107b8caebc5f5d5e5e5d5a1"), "title" : "The Great Gatsby", "author" : "F. Scott Fitzgerald", "price" : 25 }

{ "_id" : ObjectId("6107b8caebc5f5d5e5e5d5a2"), "title" : "To Kill a Mockingbird", "author" : "Harper Lee", "price" : 23 }

{ "_id" : ObjectId("6107b8caebc5f5d5e5e5d5a3"), "title" : "1984", "author" : "George Orwell", "price" : 20 }

{ "_id" : ObjectId("6107b8caebc5f5d5e5e5d5a4"), "title" : "The Catcher in the Rye", "author" : "J.D. Salinger", "price" : 27 }

replaceOne():

replaceOne() is a method in MongoDB used to replace a single document in a collection. It replaces the entire document with a new one, rather than updating specific fields like updateOne(). We have the collection : { "_id" : ObjectId("601234567890abcd12345678"), "name" : "John", "age" : 25 } { "_id" : ObjectId("601234567890abcd12345679"), "name" : "Mary", "age" : 30 } { "_id" : ObjectId("601234567890abcd1234567a"), "name" : "Peter", "age" : 35 }

If you want to replace the document with _id equal to 601234567890abcd12345678 with a new document, you can use the following replaceOne() method: db.customers.replaceOne({_id: ObjectId("601234567890abcd12345678")}, { name: "Jack", age: 28 }) This command will replace the document with _id equal to 601234567890abcd12345678 with a new document that has a name of "Jack" and an age of 28. The first parameter {_id: ObjectId("601234567890abcd12345678")} is a query that matches the document to be replaced. The second parameter { name: "Jack", age: 28 } is the new document to replace the existing one. After running the above command, the replaced document will look like this: { "_id" : ObjectId("601234567890abcd12345678"), "name" : "Jack", "age" : 28 } Delete Operation: 1.deleteOne(): Deletes a single document that matches the specified filter. If multiple documents match the filter, only the first one encountered will be deleted. example: db.collection.deleteOne({ name: "John" })
This command will delete the first document in the collection that has a name field equal to "John".
  1. deleteMany(): Deletes all documents that match the specified filter.

Example:

db.collection.deleteMany({ status: "inactive" }) This command will delete all documents in the collection that have a status field equal to "inactive". findOneAndDelete(): Finds a single document that matches the specified filter, deletes it, and returns the deleted document. Example:

db.collection.findOneAndDelete({ name: "John" })

This command will find the first document in the collection that has a name field equal to "John", delete it, and return the deleted document.

  1. drop(): Drops the entire collection and all its documents.

Example: db.collection.drop() This command will drop the collection and remove all its documents. It's important to note that deleting data from a collection is a destructive operation and cannot be undone. So, it's always a good practice to take a backup of your data before performing any delete operation.


Comments

Popular posts from this blog

How to Start MangoDB - Database For Begginers