MongoDB uses the find()
method to query documents in a collection. You can specify filters to get exactly the data you want.
db.students.find()
Returns all documents in the students
collection.
db.students.find({ age: 20 })
Returns students whose age
is exactly 20.
db.students.find({ age: { $gt: 18 } }) // age > 18 db.students.find({ age: { $lt: 30 } }) // age < 30 db.students.find({ age: { $gte: 21 } }) // age >= 21 db.students.find({ age: { $lte: 25 } }) // age <= 25 db.students.find({ age: { $ne: 20 } }) // age != 20
db.students.find({ age: { $gte: 18, $lte: 25 }, status: "active" })
Finds students with age between 18 and 25 (inclusive) and status "active".
db.students.find({ $or: [ { status: "active" }, { age: { $lt: 18 } } ] });
Finds students who are either active or younger than 18.
db.students.find( { age: { $gt: 18 } }, // filter { name: 1, age: 1, _id: 0 } // projection: show name, age, hide _id );
Shows only the name
and age
fields for students older than 18.
db.students.find().sort({ age: -1 }) // Sort by age descending db.students.find().sort({ name: 1 }) // Sort by name ascending
db.students.find().limit(5) // Get first 5 documents db.students.find().skip(10).limit(5) // Skip 10, then get 5 documents
find()
method returns a cursor. To see results in the Mongo shell, you can append .pretty()
for formatted output.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!