š MongoDB Queries ā Quick Reference & Guide for Developers
MongoDB is a NoSQL, document-oriented database. Instead of using tables and rows like relational databases, MongoDB stores data in JSON-like documents (called BSON). Queries in MongoDB are expressed in JavaScript-like syntax.
š§± Basic Document Example
json
{
"_id": ObjectId("abc123"),
"name": "John Doe",
"age": 30,
"skills": ["JavaScript", "MongoDB"],
"address": { "city": "Delhi", "zip": 110001 }
}
š 1. Basic Find Query
js
db.users.find({ name: "John Doe" });
Find one:
js
db.users.findOne({ age: 30 });
š§° 2. Comparison Operators
Operator | Meaning |
---|---|
$eq | Equal to |
$ne | Not equal |
$gt | Greater than |
$gte | Greater than or equal |
$lt | Less than |
$lte | Less than or equal |
Ā
js
db.users.find({ age: { $gt: 25 } });
āļø 3. Logical Operators
js
db.users.find({
$and: [{ age: { $gte: 25 } }, { city: "Delhi" }]
});
OR
js
db.users.find({
$or: [{ name: "John" }, { name: "Jane" }]
});
š§© 4. Array Queries
Match exact:
js
db.users.find({ skills: ["JavaScript", "MongoDB"] });
Match if contains:
js
db.users.find({ skills: "MongoDB" });
Match all:
js
db.users.find({ skills: { $all: ["JavaScript", "MongoDB"] } });
š§ 5. Field Selection (Projection)
js
db.users.find({ name: "John Doe" }, { age: 1, name: 1, _id: 0 });
1
= include0
= exclude
š 6. Sorting, Limiting, Skipping
js
db.users.find().sort({ age: -1 }).limit(5).skip(10);
1
= ascending-1
= descending
āļø 7. Insert Documents
js
db.users.insertOne({ name: "Alice", age: 22 });
db.users.insertMany([
{ name: "Bob", age: 25 },
{ name: "Carol", age: 28 }
]);
š ļø 8. Update Documents
Update one:
js
db.users.updateOne(
{ name: "Alice" },
{ $set: { age: 23 } }
);
Update many:
js
db.users.updateMany(
{ age: { $lt: 30 } },
{ $inc: { age: 1 } }
);
ā 9. Delete Documents
js
db.users.deleteOne({ name: "Bob" });
db.users.deleteMany({ age: { $lt: 20 } });
š§Ŗ 10. Regex, Null, Exists, Type
Regex:
js
db.users.find({ name: /jo/i }); // case-insensitive
Null check:
js
db.users.find({ phone: null });
Exists:
js
db.users.find({ phone: { $exists: true } });
Type check:
js
db.users.find({ age: { $type: "int" } });
š§° Aggregation (Intro)
js
db.users.aggregate([
{ $match: { age: { $gte: 25 } } },
{ $group: { _id: "$city", total: { $sum: 1 } } }
]);
ā Powerful for reporting, grouping, transforming data
š Helpful Tools
š§Ŗ Mongo Playground
š» Compass GUI ā Visual MongoDB tool
ā Summary
Action | Method |
---|---|
Find | find() , findOne() |
Insert | insertOne() , insertMany() |
Update | updateOne() , updateMany() |
Delete | deleteOne() , deleteMany() |
Advanced Queries | $gt , $lt , $or , $and , $in , $regex |