MONGODB Tutorial



MongoDB QUERYING


🔍 MongoDB Querying Basics

MongoDB uses the find() method to query documents in a collection. You can specify filters to get exactly the data you want.

🔸 Basic find() - Get all documents

db.students.find()
  

Returns all documents in the students collection.

🔸 Find documents with filter

db.students.find({ age: 20 })
  

Returns students whose age is exactly 20.

🔸 Find with comparison operators

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
  

🔸 Find documents with multiple conditions

db.students.find({ age: { $gte: 18, $lte: 25 }, status: "active" })
  

Finds students with age between 18 and 25 (inclusive) and status "active".

🔸 Logical operators: $and, $or, $not, $nor

db.students.find({
  $or: [
    { status: "active" },
    { age: { $lt: 18 } }
  ]
});
  

Finds students who are either active or younger than 18.

🔸 Projection - Return specific fields

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.

🔸 Sorting results

db.students.find().sort({ age: -1 })  // Sort by age descending
db.students.find().sort({ name: 1 })  // Sort by name ascending
  

🔸 Limit and skip

db.students.find().limit(5)      // Get first 5 documents
db.students.find().skip(10).limit(5)  // Skip 10, then get 5 documents
  
Note: The find() method returns a cursor. To see results in the Mongo shell, you can append .pretty() for formatted output.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review