CRUD Operations in MongoDB
create, read , update, and delete documents within the collections.
Table of contents
Insert Operation
Documents can be inserted using insertOne()
and insertMany()
methods.
db.<collectionname>.insertOne({field1:value1, field2: value2})
db.<collectionname>.insertMany([
{field1:value1, field2: value2},
{field1:value1,field2:value2}
])
Let us see an Example:
Insert one document in a collection named fruits
db.fruits.insertOne({ Name:"Mango", season: "Summer", isAvailable:true})
Insert multiple documents in a collection named fruits
db.fruits.insertMany([ { Name:"Water Melon", season: "Summer", isAvailable:true}, { Name:"Custard Apple", season: "Monsoon", isAvailable:true}, { Name:"Pomo granate", season: "Monsoon", isAvailable:true} ])
Read Operation
Documents in collections can be retrieved by using find() method.
db.<collectionname>.find(<query>,<projection>)
Let us see with an example:
Finding all the documents or fruits which are available in summer
db.fruits.find({season:"Summer"})
To get certain number of top documents or fruits whose value of season is "Summer"
limit()
method is used.db.fruits.find({season:"Summer"}).limit(3)
To skip certain number of top documents
skip()
method is used.db.fruits.find({season:"Summer"}).skip(1)
Update Operation
To update a document in a collection in MongoDB, you can use the update()
or updateOne()
method. Here's an example of how to update a document using the MongoDB shell. The following are the syntax to update single and multiple documents
updateOne()
db.colname.updateOne(
{ _id: ObjectId("yourDocumentId") }, // The query to match the document
{ $set: { keyToUpdate: newValue } } // The update operation using $set
);
updateMany()
db.colname.updateMany(
{keytomatch :valuetomatch},// The query to match the document
{$set:{keytoupdate: newvalue}} // The update operation using $set
);
Let us see with an example:
To update an only one document
from isAvailable: true to isAvaiable: false
.dob.fruits.updateOne({isAvailable:true}, {$set: {isAvailable:false}} );
To update all documents in collection from key-value as
isAvailable: true to isAvailable: false
.dob.fruits.updateMany({isAvailable:true}, {$set:{isAvailable:false}} );
Delete Operation
To delete documents from a collection in MongoDB, you can use the deleteOne()
or deleteMany()
method, depending on whether you want to delete a single document or multiple documents that match certain criteria.
The syntax for the delete query:
deleteOne()
db.collname.deleteOne({keytofind:valuetofind})
deleteMany()
db.collname.deleteMany({keytofind:valuetofind})
Let us understand with an example:
The query to delete the first and only one document that contains key-value pair
season: "Summer"
db.fruits.deleteOne({season: "Summer"})
The query to delete all the documents that contain key-value pair
season: "Summer"
db.fruits.deleteMany({season: "Summer"})