MongoDB in MongoDB is best learned by connecting the rule to a product catalog or user activity store. Start with the smallest collection query, observe the output, and then add one realistic constraint so the concept becomes practical.
The key habit for this lesson is to watch document shape and index as it changes. That makes the topic easier to debug, easier to explain in interviews, and easier to use in real code without memorizing isolated syntax.
CRUD stands for Create, Read, Update, and Delete - the four fundamental operations for managing data in any database. In MongoDB, these operations work on documents within collections using the MongoDB Query Language (MQL).
Use insertOne() to add a single document, or insertMany() to add multiple documents at once. MongoDB automatically generates a unique _id field (ObjectId) if you don't provide one.
// Switch to the database
use myapp
// Insert a single document
db.users.insertOne({
name: "Alice Johnson",
email: "alice@example.com",
age: 29,
role: "admin",
active: true,
createdAt: new Date()
})
// Output: { acknowledged: true, insertedId: ObjectId("...") }
// Insert multiple documents at once
db.users.insertMany([
{ name: "Bob Smith", email: "bob@example.com", age: 34, role: "user", active: true },
{ name: "Carol White", email: "carol@example.com", age: 27, role: "user", active: false },
{ name: "Dave Brown", email: "dave@example.com", age: 41, role: "editor", active: true }
])
// Output: { acknowledged: true, insertedIds: { '0': ObjectId("..."), '1': ObjectId("..."), ... } }
Use find() to retrieve multiple documents and findOne() to retrieve the first matching document. Pass a filter object to narrow results, and a projection object to control which fields are returned.
// Find all documents in the collection
db.users.find()
// Find with a filter - all active users
db.users.find({ active: true })
// Find one document - first admin user
db.users.findOne({ role: "admin" })
// Find with multiple conditions
db.users.find({ active: true, role: "user" })
// Projection: include only name and email (exclude _id)
db.users.find({ active: true }, { name: 1, email: 1, _id: 0 })
// Sort, limit, and skip
db.users.find({ active: true })
.sort({ age: -1 }) // sort by age descending
.limit(10) // return max 10 results
.skip(0) // skip 0 (pagination)
// Count matching documents
db.users.countDocuments({ active: true })
// Query nested field using dot notation
db.users.find({ "address.city": "New York" })
// Query array field - users who have "reading" as a hobby
db.users.find({ hobbies: "reading" })
// Find by ObjectId
db.users.findOne({ _id: ObjectId("64a1f2c3e4b0a1b2c3d4e5f6") })
// Find users aged between 25 and 35
db.users.find({ age: { $gte: 25, $lte: 35 } })
MongoDB provides updateOne(), updateMany(), and replaceOne(). Always use update operators like $set to modify specific fields - without them you would replace the entire document.
// Update a single document - change Alice's age
db.users.updateOne(
{ name: "Alice Johnson" }, // filter
{ $set: { age: 30, role: "superadmin" } } // update
)
// Update multiple documents - deactivate all "user" role accounts
db.users.updateMany(
{ role: "user" },
{ $set: { active: false } }
)
// Increment a field - add 1 to loginCount
db.users.updateOne(
{ email: "alice@example.com" },
{ $inc: { loginCount: 1 } }
)
// Upsert - insert if not found, update if found
db.users.updateOne(
{ email: "newuser@example.com" },
{ $set: { name: "New User", role: "user", active: true } },
{ upsert: true }
)
// Replace entire document (keeps _id)
db.users.replaceOne(
{ email: "bob@example.com" },
{ name: "Bob Smith", email: "bob@example.com", age: 35, role: "editor", active: true }
)
Use deleteOne() to remove the first matching document, or deleteMany() to remove all matching documents. Passing an empty filter {} to deleteMany() removes all documents from the collection.
// Delete a single document
db.users.deleteOne({ email: "carol@example.com" })
// Output: { acknowledged: true, deletedCount: 1 }
// Delete all inactive users
db.users.deleteMany({ active: false })
// Output: { acknowledged: true, deletedCount: 2 }
// Delete all documents in a collection (use with caution!)
db.users.deleteMany({})
// Find and delete in one operation (returns the deleted document)
db.users.findOneAndDelete({ email: "dave@example.com" })
// CREATE
db.collection.insertOne({ ... })
db.collection.insertMany([{ ... }, { ... }])
// READ
db.collection.find(filter, projection)
db.collection.findOne(filter, projection)
db.collection.countDocuments(filter)
// UPDATE
db.collection.updateOne(filter, update, options)
db.collection.updateMany(filter, update, options)
db.collection.replaceOne(filter, replacement, options)
db.collection.findOneAndUpdate(filter, update, options)
// DELETE
db.collection.deleteOne(filter)
db.collection.deleteMany(filter)
db.collection.findOneAndDelete(filter)
Use MongoDB when the program needs a clear answer to a specific problem, not because the keyword looks familiar. In a real MongoDB task, first name the input, then name the transformation, then name the output. This small discipline shows whether the topic is being used correctly or only copied from an example.
A reliable practice flow is: create the smallest working collection query, add one normal case, add one edge case such as missing, repeated, empty, or boundary input, and then confirm the result with explain plan and sample documents. If the result surprises you, reduce the code until the behavior is visible again.
The most common trap here is copying the syntax before understanding the behavior. Avoid it by writing one sentence before the code that explains why MongoDB is the right choice. After the code runs, verify the lesson by doing this: change one input and explain the changed output.
Copying the syntax before understanding the behavior.
Write the expected behavior first, then make the example prove it.
Practicing only the perfect input.
Also test missing, repeated, empty, or boundary input before considering the lesson complete.
Looking only at the final output.
Trace document shape and index through each important step.
Use it when the problem matches the behavior shown in the example and when the result can be verified through explain plan and sample documents.
Start with a tiny case, then test missing, repeated, empty, or boundary input. The main warning sign is copying the syntax before understanding the behavior.
Trace document shape and index, predict the result, run the example, and compare your prediction with the actual output.
Explore 500+ free tutorials across 20+ languages and frameworks.