Tutorials Logic, IN info@tutorialslogic.com

MongoDB CRUD insertOne, find, update, delete

MongoDB CRUD insertOne, find, update, delete

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.

What are CRUD Operations?

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).

Create - Inserting Documents

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.

insertOne() and insertMany()

insertOne() and insertMany()
// 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("..."), ... } }

Read - Querying Documents

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(), findOne(), and Projections

find(), findOne(), and Projections
// 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 })

Querying Nested Fields and Arrays

Querying Nested Fields and Arrays
// 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 } })

Update - Modifying Documents

MongoDB provides updateOne(), updateMany(), and replaceOne(). Always use update operators like $set to modify specific fields - without them you would replace the entire document.

updateOne(), updateMany(), replaceOne()

updateOne(), updateMany(), replaceOne()
// 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 }
)

Delete - Removing Documents

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.

deleteOne() and deleteMany()

deleteOne() and deleteMany()
// 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" })

CRUD Quick Reference

CRUD Quick Reference
// 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)

Applied guide for MongoDB

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.

  • Identify the exact problem solved by MongoDB.
  • Trace document shape and index before and after the main operation.
  • Keep one intentionally broken version and explain the fix.
  • Connect the example to a product catalog or user activity store so the idea feels concrete.
Key Takeaways
  • I can explain where MongoDB fits inside a product catalog or user activity store.
  • I can point to the exact document shape and index affected by this topic.
  • I tested a normal case and an edge case involving missing, repeated, empty, or boundary input.
  • I verified the result with explain plan and sample documents instead of assuming it worked.
  • I can describe the main mistake: copying the syntax before understanding the behavior.
Common Mistakes to Avoid
WRONG Copying the syntax before understanding the behavior.
RIGHT Write the expected behavior first, then make the example prove it.
A one-line expectation turns the code from copied syntax into a testable idea.
WRONG Practicing only the perfect input.
RIGHT Also test missing, repeated, empty, or boundary input before considering the lesson complete.
The edge case is where most interview follow-up questions begin.
WRONG Looking only at the final output.
RIGHT Trace document shape and index through each important step.
Tracing makes debugging faster because you can see the first incorrect state.

Practice Tasks

  • Build one small collection query that demonstrates MongoDB in a product catalog or user activity store.
  • Change the example to include missing, repeated, empty, or boundary input and record the difference.
  • Break the example by deliberately copying the syntax before understanding the behavior, then write the corrected version.
  • Explain the finished example in five bullet points: input, operation, output, failure case, and verification.

Frequently Asked Questions

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.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.