MongoDB CRUD
What Is CRUD?
CRUD stands for Create, Read, Update, and Delete: the four things you do with data. In MongoDB each has a method on the collection: insertOne() and insertMany() create, find() and findOne() read, updateOne() and updateMany() update, and deleteOne() and deleteMany() delete. Each one takes a filter document that says which documents it applies to.
Why It Matters
| Reason | Benefit |
|---|---|
| Four verbs cover most apps | Almost every feature is built from creating, reading, updating, or deleting documents. |
| Consistent filter syntax | The same filter document works for find, update, and delete, so you learn it once. |
| Informative results | Write methods return counts such as matchedCount and deletedCount so you can verify what happened. |
| Atomic single-document writes | Each write to one document is atomic, even when it touches nested fields and arrays. |
How To Use It
- Use a practice database: use shop.
- Create data with insertOne() then insertMany() on db.products.
- Read with db.products.find() and narrow it with a filter such as { price: { $lt: 50 } }.
- Update one product with updateOne({ sku: "A1" }, { $set: { price: 19 } }).
- Update many with updateMany({ stock: 0 }, { $set: { status: "out" } }).
- Check matchedCount and modifiedCount in the returned result.
- Delete with deleteOne() for a single match or deleteMany() for a set.
- Always run find() with the same filter first before calling deleteMany().
mongosh Examples
use shop
// Create
db.products.insertOne({ sku: "A1", name: "Pen", price: 12, stock: 100 })
db.products.insertMany([
{ sku: "B2", name: "Notebook", price: 45, stock: 20 },
{ sku: "C3", name: "Stapler", price: 80, stock: 0 }
])
// Read
db.products.find()
db.products.find({ price: { $lt: 50 } })
db.products.findOne({ sku: "B2" })
// Update
db.products.updateOne({ sku: "A1" }, { $set: { price: 15 } })
db.products.updateMany({ stock: 0 }, { $set: { status: "out-of-stock" } })
// Upsert: insert if no match
db.products.updateOne(
{ sku: "D4" },
{ $set: { name: "Ruler", price: 8 } },
{ upsert: true }
)
// Delete
db.products.deleteOne({ sku: "A1" })
db.products.deleteMany({ status: "out-of-stock" }) Edge Cases & Pitfalls
Empty filter matches everything
deleteMany({}) removes all documents in the collection, and updateMany({}, ...) changes all of them. Preview with find() first.
updateOne affects only one match
If several documents match, only the first one found is updated. Use a unique field such as _id for precision.
Update needs operators
db.c.updateOne(filter, { price: 5 }) fails. Use { $set: { price: 5 } } or replaceOne() for a full replacement.
insertMany stops on error by default
With ordered inserts, the first error halts the rest. Pass { ordered: false } to continue past failures.
Cheat Sheet
| Topic | Detail |
|---|---|
| insertOne(doc) | Insert one document; returns acknowledged and insertedId |
| insertMany([docs]) | Insert an array of documents; returns insertedIds |
| find(filter) | Return a cursor over all matching documents |
| findOne(filter) | Return the first matching document or null |
| updateOne(filter, update) | Update the first match using operators like $set |
| updateMany(filter, update) | Update every matching document |
| deleteOne(filter) | Delete the first matching document |
| deleteMany(filter) | Delete every matching document; {} deletes all |
| upsert: true | Insert a new document if the filter matches nothing |
| countDocuments(filter) | Count matches without fetching them |
Key Takeaways
Update operations need an update operator such as $set. A plain document as the second argument to updateOne() is rejected; use replaceOne() to replace a whole document.
Frequently Asked Questions
What does CRUD mean in MongoDB?
Create, Read, Update, Delete. In mongosh these map to insertOne/insertMany, find/findOne, updateOne/updateMany, and deleteOne/deleteMany.
What is the difference between find and findOne?
find returns a cursor over all matches. findOne returns a single document, or null when nothing matches.
What is an upsert?
An update with upsert: true inserts a new document built from the filter and update when no document matches.
How do I delete all documents but keep the collection?
Run db.collection.deleteMany({}). It removes every document but keeps the collection and its indexes.
How do I know if an update worked?
Check the result: matchedCount is how many documents matched the filter and modifiedCount is how many actually changed.
Are MongoDB writes atomic?
A write to a single document is atomic. Writes spanning multiple documents are not atomic unless you use a transaction.
Next: MongoDB Queries
Continue the MongoDB learning path.
CODETOFUN NEWS
Stay Ahead in Tech
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
8 people found this page helpful
