Click any item to expand the explanation and examples.
📝 CRUD
insertOne / insertMany create
db.users.insertOne({ name: "Alice", email: "alice@example.com", age: 30 })
db.users.insertMany([
{ name: "Bob", age: 25 },
{ name: "Charlie", age: 35 }
])
find / findOne read
db.users.find() // All documents
db.users.find({ age: { $gt: 25 } }) // Where age > 25
db.users.findOne({ email: "alice@example.com" })
db.users.find({}, { name: 1, email: 1 }) // Projection (select fields)
db.users.find().sort({ age: -1 }) // Sort descending
db.users.find().limit(10).skip(20) // Pagination
db.users.countDocuments({ age: { $gt: 25 } })
updateOne / updateMany update
db.users.updateOne(
{ email: "alice@example.com" },
{ $set: { age: 31 } }
)
db.users.updateMany(
{ age: { $lt: 18 } },
{ $set: { status: "minor" } }
)
// Other update operators
{ $inc: { age: 1 } } // Increment
{ $unset: { temp: "" } } // Remove field
{ $push: { tags: "new" } } // Add to array
{ $pull: { tags: "old" } } // Remove from array
{ $addToSet: { tags: "unique" } } // Add if not exists
deleteOne / deleteMany delete
db.users.deleteOne({ email: "alice@example.com" })
db.users.deleteMany({ status: "inactive" })
db.users.deleteMany({}) // Delete all documents
🔍 Query Operators
Comparison and logical operators query
// Comparison
{ age: { $eq: 30 } } // Equal
{ age: { $ne: 30 } } // Not equal
{ age: { $gt: 25 } } // Greater than
{ age: { $gte: 25 } } // Greater than or equal
{ age: { $lt: 30 } } // Less than
{ age: { $in: [25, 30] } } // In array
{ age: { $nin: [25, 30] } } // Not in array
// Logical
{ $and: [{ age: { $gt: 20 } }, { age: { $lt: 30 } }] }
{ $or: [{ status: "active" }, { role: "admin" }] }
{ age: { $not: { $gt: 30 } } }
// Element
{ email: { $exists: true } }
{ age: { $type: "number" } }
// Regex
{ name: { $regex: /^ali/i } }
📊 Aggregation
Aggregation pipeline aggregate
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: {
_id: "$customerId",
totalSpent: { $sum: "$amount" },
orderCount: { $sum: 1 }
}},
{ $sort: { totalSpent: -1 } },
{ $limit: 10 }
])
// Lookup (join)
db.orders.aggregate([
{ $lookup: {
from: "users",
localField: "customerId",
foreignField: "_id",
as: "customer"
}},
{ $unwind: "$customer" }
])
⚡ Indexes
createIndex / getIndexes index
db.users.createIndex({ email: 1 }) // Single field
db.users.createIndex({ email: 1 }, { unique: true }) // Unique
db.users.createIndex({ name: 1, age: -1 }) // Compound
db.users.createIndex({ bio: "text" }) // Text search
db.users.getIndexes() // List indexes
db.users.dropIndex("email_1") // Drop index
See also: What is MongoDB? | What is JSON?