How do you perform CRUD operations in MongoDB?
The four CRUD operations in MongoDB are exposed as collection methods.
Create —
insertOne()andinsertMany().Read —
find()(multi-doc cursor),findOne(),aggregate()for pipelines.Update —
updateOne(),updateMany(),replaceOne(); uses operators like$set,$inc,$push.Delete —
deleteOne(),deleteMany().Bulk operations —
bulkWrite()for batched mixed writes.Atomic at document level — single-document writes are atomic; multi-document need transactions.
// CREATE
db.users.insertOne({ name: 'John', age: 30, email: 'john@test.com' });
db.users.insertMany([
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 35 }
]);
// READ
db.users.find({ age: { $gt: 25 } }); // age > 25
db.users.find({ name: { $in: ['Alice', 'Bob'] } }); // name in list
db.users.findOne({ email: 'john@test.com' }); // first match
db.users.find({ age: { $gte: 25 } }, { name: 1, age: 1, _id: 0 }); // projection
// UPDATE
db.users.updateOne(
{ name: 'John' },
{ $set: { age: 31 }, $push: { hobbies: 'coding' } }
);
db.users.updateMany(
{ age: { $lt: 30 } },
{ $inc: { age: 1 } } // Increment age by 1
);
// DELETE
db.users.deleteOne({ name: 'Bob' });
db.users.deleteMany({ age: { $lt: 20 } }); // Delete all matching
// UPSERT (update or insert if not found)
db.users.updateOne(
{ email: 'new@test.com' },
{ $set: { name: 'New User', age: 28 } },
{ upsert: true }
);insertOne/insertMany create documents. find with query operators filters results. Projection { name: 1, _id: 0 } includes name, excludes _id. $set updates specific fields without replacing the whole document. $inc atomically increments values. $push adds to arrays. upsert: true creates the document if the filter matches nothing.
Know the major query operators ($gt, $in, $regex, $exists) and update operators ($set, $inc, $push, $pull, $addToSet). The difference between updateOne and replaceOne (update modifies fields, replace replaces the entire document).
Upsert for create-or-update patterns.