CRUD Operations using MongoDB
CRUD Operations Cheat Sheet
Let us understand how can we perform CRUD operations in MongoDB.
- CRUD stands for Create, Read, Update and Delete
- We can create documents using the InsertOne function.
{ "item" : "canvas",
"qty" : 100,
"tags" : ["cotton"],
"size" : { "h" : 28, "w" : 35.5, "uom" : "cm" }
}
)
- find or findOne can be used the documents from the collection, while find returns all the documents matching condition,findOne returns only first document
- Update function can be used to update an existing document , if we set upsert as true then the documents will be inserted if it does not exist.
- We can only perform operations such as $min, $max, $inc, $set etc as part of update. It is not possible to derive data from existing fields and update by using functions such as lower, upper, etc.
- Following are the functions which can be used to update.
- update(same as updateOne)
- updateMany(updates multiple documents)
{ "qty" : { $lt: 50 } }, // specifies the documents to update
{
$set: { "size.uom" : "cm", "status": "P" },
$currentDate : { "lastModified": true }
}
)
- updateOne
{ "item" : "paper" }, // specifies the document to update
{
$set: { "size.uom" : "cm", "status" : "P" },
$currentDate: { "lastModified": true }
}
)
- Data can be deleted using functions such as deleteMany, deleteOne ,findOneAndDelete.
- The following operation deletes the first document with
status
equal toD
:
{ "status": "D" } // specifies the document to delete
)
- The following operation deletes all of the documents in the specified
inventory
collection withstatus
equal toA
:
{ "status" : "A" } // specifies the documents to delete
)
No comments
If you have any doubts, Please let me know