MongoDB provides an expressive, declarative JSON-based query syntax for retrieving and updating documents.
1. Query Operators: Comparison & Logic
// 1. Comparison Operators ($eq, $ne, $gt, $gte, $lt, $lte, $in, $nin)
// Find products with price between 20 and 100
db.products.find({
price: { $gte: 20, $lte: 100 }
});
// Find products in specific categories
db.products.find({
category: { $in: ["electronics", "software", "accessories"] }
});
// 2. Logical Operators ($and, $or, $nor, $not)
// Find active users who are either admins OR have VIP status
db.users.find({
is_active: true,
$or: [
{ role: "admin" },
{ loyalty_tier: "VIP" }
]
});
// 3. Element Operators ($exists, $type)
// Find documents where a phone number field is present and is a string
db.contacts.find({
phone: { $exists: true, $type: "string" }
});
2. Querying Arrays & Nested Objects
MongoDB uses dot notation to query deep inside arrays and subdocuments:
// Querying a nested object property
db.orders.find({
"shipping_address.city": "Austin"
});
// Querying elements inside an array of objects
db.orders.find({
"items.sku": "PROD-PYTHON-BOOK"
});
// Using $elemMatch when multiple conditions must match the SAME array element
db.students.find({
grades: {
$elemMatch: { subject: "Computer Science", score: { $gte: 90 } }
}
});
3. Updating Documents: Atomicity & Update Operators
Never replace an entire document unless explicitly intended. Always use atomic update operators:
// $set: Update or add fields
// $inc: Increment numerical counters atomically
// $currentDate: Set timestamps
db.users.updateOne(
{ email: "sarah@codeacademix.dev" },
{
$set: { "preferences.newsletter": false },
$inc: { login_count: 1 },
$currentDate: { last_login: true }
}
);
// Array Update Operators ($push, $addToSet, $pull)
// $addToSet adds an element only if it does NOT already exist (Set behavior)
db.users.updateOne(
{ _id: ObjectId("655f19001c2b3a0011e5c4a2") },
{ $addToSet: { skills: "MongoDB" } }
);
// $pull removes matching elements from an array
db.users.updateOne(
{ _id: ObjectId("655f19001c2b3a0011e5c4a2") },
{ $pull: { skills: "LegacySQL" } }
);