Skip to main content

MongoDB Queries

Query Operators

Comparison Operators

// Equal
db.users.find({ age: 30 });

// Not equal
db.users.find({ age: { $ne: 30 } });

// Greater than
db.users.find({ age: { $gt: 25 } });

// Greater than or equal
db.users.find({ age: { $gte: 25 } });

// Less than
db.users.find({ age: { $lt: 40 } });

// Less than or equal
db.users.find({ age: { $lte: 40 } });

// In array
db.users.find({ status: { $in: ["active", "pending"] } });

// Not in array
db.users.find({ status: { $nin: ["banned", "deleted"] } });

Logical Operators

// AND (implicit)
db.users.find({ age: { $gte: 25 }, status: "active" });

// AND (explicit)
db.users.find({
$and: [
{ age: { $gte: 25 } },
{ status: "active" }
]
});

// OR
db.users.find({
$or: [
{ age: { $lt: 18 } },
{ age: { $gt: 65 } }
]
});

// NOT
db.users.find({ age: { $not: { $gt: 30 } } });

// NOR
db.users.find({
$nor: [
{ status: "banned" },
{ age: { $lt: 13 } }
]
});

Element Operators

// Field exists
db.users.find({ email: { $exists: true } });

// Field doesn't exist
db.users.find({ phone: { $exists: false } });

// Type check
db.users.find({ age: { $type: "number" } });
db.users.find({ age: { $type: 16 } }); // 16 = 32-bit integer

Array Operators

// Array contains value
db.users.find({ tags: "premium" });

// Array contains all values
db.users.find({ tags: { $all: ["premium", "verified"] } });

// Array size
db.users.find({ tags: { $size: 3 } });

// Array element match
db.users.find({
"scores": {
$elemMatch: { $gte: 80, $lt: 85 }
}
});

Nested Field Queries

// Dot notation
db.users.find({ "profile.age": 30 });
db.users.find({ "address.city": "New York" });

// Nested object match
db.users.find({
profile: {
age: 30,
location: "SF"
}
}); // Exact match

// Partial nested match
db.users.find({ "profile.age": 30 });

Regular Expression Queries

// Case-insensitive search
db.users.find({ name: /john/i });

// Starts with
db.users.find({ name: /^John/ });

// Ends with
db.users.find({ email: /\.com$/ });

// Contains
db.users.find({ description: /mongodb/ });

// Using $regex operator
db.users.find({
name: {
$regex: "john",
$options: "i"
}
});
// Create text index first
db.articles.createIndex({ title: "text", content: "text" });

// Text search
db.articles.find({ $text: { $search: "mongodb database" } });

// Text search with score
db.articles.find(
{ $text: { $search: "mongodb" } },
{ score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } });

// Exact phrase search
db.articles.find({ $text: { $search: "\"exact phrase\"" } });

// Exclude terms
db.articles.find({ $text: { $search: "mongodb -sql" } });

Projection (Select Fields)

// Include specific fields
db.users.find({}, { name: 1, email: 1 });

// Exclude specific fields
db.users.find({}, { password: 0, _id: 0 });

// Include nested fields
db.users.find({}, { "profile.age": 1, name: 1 });

// Array element projection
db.users.find({}, { "scores": { $slice: 3 } }); // First 3 elements
db.users.find({}, { "scores": { $slice: -2 } }); // Last 2 elements
db.users.find({}, { "scores": { $slice: [1, 3] } }); // Skip 1, limit 3

Sorting and Limiting

// Sort ascending
db.users.find().sort({ age: 1 });

// Sort descending
db.users.find().sort({ age: -1 });

// Multiple field sort
db.users.find().sort({ status: 1, age: -1 });

// Limit results
db.users.find().limit(10);

// Skip results (pagination)
db.users.find().skip(20).limit(10);

// Count documents
db.users.countDocuments({ status: "active" });