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.
db.inventory.insertOne(
{ “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
myCursor = db.inventory.find( { status: “D” } )
- 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)
db.inventory.updateMany(
- updateOne
db.inventory.updateOne(
- Data can be deleted using functions such as deleteMany, deleteOne ,findOneAndDelete.
- The following operation deletes the first document with
status
equal toD
:
db.inventory.deleteOne(
- The following operation deletes all of the documents in the specified
inventory
collection withstatus
equal toA
:
db.inventory.deleteMany(