MongoDB Query Cookbook
Leading document-oriented NoSQL database managing schema-less JSON-like BSON objects. 10 production-tested query recipes ready to copy and execute.
1. Multi-Stage Aggregation Pipeline ($match & $group)
Filter, group, and calculate totals over document collections.
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: {
_id: "$customerId",
totalSpent: { $sum: "$amount" },
orderCount: { $sum: 1 }
}},
{ $sort: { totalSpent: -1 } }
]); 2. Left Outer Join Collections ($lookup)
Join related documents from secondary collection.
db.orders.aggregate([
{ $lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "userInfo"
}},
{ $unwind: "$userInfo" }
]); 3. Update Document with Upsert Option
Modify matching document or insert new object if missing.
db.users.updateOne(
{ email: "alex@example.com" },
{
$set: { name: "Alex", lastActive: new Date() },
$inc: { loginCount: 1 }
},
{ upsert: true }
); 4. Text Search Index & Query
Create text index and run natural language searches.
db.articles.createIndex({ title: "text", content: "text" });
db.articles.find(
{ $text: { $search: "database query optimization" } },
{ score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } }); 5. Geospatial Near Location Search ($near)
Find documents near geographical coordinates.
db.places.createIndex({ location: "2dsphere" });
db.places.find({
location: {
$near: {
$geometry: { type: "Point", coordinates: [ -73.9667, 40.78 ] },
$maxDistance: 5000
}
}
}); 6. Push Element to Array Field ($push)
Add unique element to document array field.
db.users.updateOne(
{ _id: ObjectId("60d5ec49f1a2c80015f8e123") },
{ $addToSet: { tags: "premium" } }
); 7. Build Compound Index Background
Create multi-field index without locking write operations.
db.logs.createIndex(
{ status: 1, timestamp: -1 },
{ background: true }
); 8. Auto-Expire Documents with TTL Index
Set automatic document deletion after expiration interval.
db.sessions.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 3600 }
); 9. Enforce Document JSON Schema
Add strict structural validation rules to collection.
db.createCollection("products", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "price"],
properties: {
name: { bsonType: "string" },
price: { bsonType: "double", minimum: 0 }
}
}
}
}); 10. Inspect Aggregation Plan Execution
Inspect query execution statistics using explain().
db.orders.explain("executionStats").find({ status: "pending" }); Test your MongoDB architectural knowledge!
Practice key concepts, memory structures, and indexing questions with flashcards.