After this lesson, you will be able to: Use CRUD operations: insertOne/insertMany, find/findOne, updateOne/updateMany, deleteOne/deleteMany.
Mongo's CRUD API is verbose compared to SQL but explicit. Once memorized, it's predictable.
Single + bulk inserts.
// Single doc// → returns { acknowledged: true, insertedId: ObjectId("...") }// Many docs (atomic per-doc; partial inserts possible if errors)db.users.insertMany([], { ordered: false }); // ordered:false continues after errors
Query filter syntax.
// Alldb.users.find();// Filterdb.users.find({ age: 30 });db.users.find({ "address.city": "NYC" }); // nested field// Projection, only return specific fields (1 = include, 0 = exclude)db.users.find({ age: 30 }, { name: 1, email: 1, _id: 0 });// Sort + limit + skip (pagination)db.users.find().sort({ createdAt: -1 }).limit(10).skip(20);// findOne, single doc or null// Countdb.users.countDocuments({ age: { $gte: 18 } });
Atomic update operators.
// Update one (first match)db.users.updateOne({ $set: { name: "Alex Chen", updatedAt: new Date() } });// Update manydb.users.updateMany({ active: false },{ $set: { archivedAt: new Date() } });// Common operators// $set, set field// $unset, remove field// $inc, increment a numeric field// $push, append to array// $addToSet, append if not already present// $pull, remove matching elements from array// $currentDate, set to current date// Example: increment a counter + push to array atomicallydb.posts.updateOne({ _id: postId },{$inc: { viewCount: 1 },$push: { recentViewers: { userId, at: new Date() } }});// Upsert (insert if not found)db.users.updateOne({ $set: { name: "New", createdAt: new Date() } },{ upsert: true });
Same pattern as update.
// Delete one// Delete manydb.users.deleteMany({ archivedAt: { $exists: true } });// Soft delete pattern (mark instead of remove)db.users.updateOne({ _id: userId },{ $set: { deletedAt: new Date() } });// Then your app filters out { deletedAt: null }
Forgetting $set: `updateOne({_id}, { name: 'X' })` REPLACES the entire doc. Read-modify-write instead of atomic operators (lost-update bug). deleteMany({}), empties the collection (forgot the filter? Disaster). Not handling 'not found' on updateOne (matchedCount = 0 silently).
Sign in and purchase access to unlock this lesson.