MongoDB CRUD Operations
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.
// 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 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 } })
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.
// 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.
// 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)