MongoDB 8 cheatsheet
MongoDB 8: Create, read, update, delete
13 common MongoDB 8 tasks.
Insert a document
Add one document to a collection.
db.users.insertOne({ name: "Ada", email: "[email protected]", age: 36 })
Insert several documents
Add an array of documents in one call.
db.users.insertMany([{ name: "Grace" }, { name: "Linus" }])
Find all documents
Return documents from a collection. The shell shows the first 20.
db.users.find()
Find with a filter and projection
Find users older than 30 and return only their names.
db.users.find({ age: { $gt: 30 } }, { name: 1, _id: 0 })
Find one document
Return the first document that matches.
db.users.findOne({ email: "[email protected]" })
Sort and paginate
Return the 10 newest documents, skipping the first 20.
db.users.find().sort({ createdAt: -1 }).skip(20).limit(10)
Count matching documents
Count the documents that match a filter.
db.users.countDocuments({ active: true })
Update a document
Set fields on the first matching document.
db.users.updateOne({ email: "[email protected]" }, { $set: { age: 37 } })
Update many documents
Increase a counter on every matching document.
db.users.updateMany({ active: true }, { $inc: { logins: 1 } })
Update or insert
Update a document, or insert it when none matches.
db.users.updateOne({ email: "[email protected]" }, { $set: { name: "New" } }, { upsert: true })
Delete one document
Delete the first matching document.
db.users.deleteOne({ email: "[email protected]" })
Delete many documents
Delete every document that matches the filter.
db.users.deleteMany({ active: false })
Caution: An empty filter {} deletes every document in the collection. Test the filter with find() first.