Before running queries, ensure you’re using the correct database.
use myDatabase
Let’s assume we have a users
collection with the following documents:
db.users.find().pretty()
Sample Data:
[
{ "_id": 1, "name": "Alice", "age": 28, "city": "New York" },
{ "_id": 2, "name": "Bob", "age": 34, "city": "Los Angeles" },
{ "_id": 3, "name": "Charlie", "age": 23, "city": "Chicago" },
{ "_id": 4, "name": "David", "age": 30, "city": "New York" }
]
Comparison operators filter data based on specific conditions.
$gt
(Greater Than)Find users older than 25:
db.users.find({ age: { $gt: 25 } })
✅ Returns users with age
greater than 25.
$lt
(Less Than)Find users younger than 30:
db.users.find({ age: { $lt: 30 } })
✅ Returns users with age
less than 30.
$gte
& $lte
(Greater/Less Than or Equal)Find users aged between 25 and 30:
db.users.find({ age: { $gte: 25, $lte: 30 } })
Logical operators combine multiple conditions.
$and
OperatorFind users from New York who are older than 25:
db.users.find({ $and: [{ city: "New York" }, { age: { $gt: 25 } }] })
✅ Returns users from New York with age
greater than 25.
$or
OperatorFind users who are either from New York or Chicago:
db.users.find({ $or: [{ city: "New York" }, { city: "Chicago" }] })
✅ Returns users from New York OR Chicago.
$not
OperatorFind users not from Los Angeles: