MongoDB provides a rich set of query operators to perform complex queries on your data.
// Greater than
db.users.find({ age: { $gt: 25 } })
// Less than or equal to
db.users.find({ age: { $lte: 30 } })
// Not equal to
db.users.find({ status: { $ne: "inactive" } })
// In array
db.users.find({ role: { $in: ["admin", "editor"] } })
// AND condition
db.users.find({
age: { $gt: 25 },
status: "active"
})
// OR condition
db.users.find({
$or: [
{ age: { $lt: 25 } },
{ status: "premium" }
]
})
// AND with OR
db.users.find({
status: "active",
$or: [
{ age: { $lt: 25 } },
{ role: "admin" }
]
})
// Sort by age ascending
db.users.find().sort({ age: 1 })
// Sort by multiple fields
db.users.find().sort({ status: 1, age: -1 })
// Include only name and email
db.users.find({}, { name: 1, email: 1, _id: 0 })
// Exclude status field
db.users.find({}, { status: 0 })
// Limit to 10 results
db.users.find().limit(10)
// Skip first 5 results
db.users.find().skip(5)
// Combine limit and skip
db.users.find().skip(5).limit(10)
// Match array element
db.users.find({ tags: "mongodb" })
// Match all array elements
db.users.find({ tags: { $all: ["mongodb", "nodejs"] } })
// Match array size
db.users.find({ tags: { $size: 3 } })
Now that you understand querying, you can explore: