Lesson 12 of 50 – Finding Documents in MongoDB
24%

Finding Documents in MongoDB

In MongoDB, the find() and findOne() methods are used to retrieve documents from a collection. You can display all documents, search by a specific field, use multiple conditions, and retrieve only the information you need.

In this lesson, we will practise document retrieval using a student management database.

1. Prepare the Database

Select the database:

use school

Insert some sample student records:

db.students.insertMany([
    {
        name: "Rahul",
        age: 20,
        course: "ADCA",
        city: "Patna"
    },
    {
        name: "Amit",
        age: 22,
        course: "Python",
        city: "Gaya"
    },
    {
        name: "Priya",
        age: 19,
        course: "Web Development",
        city: "Patna"
    },
    {
        name: "Neha",
        age: 21,
        course: "Python",
        city: "Aurangabad"
    },
    {
        name: "Ravi",
        age: 23,
        course: "ADCA",
        city: "Gaya"
    }
])

Note: Run this insertion example only once if you do not want duplicate sample records.

2. Find All Documents

The find() method without a filter retrieves all documents in a collection.

db.students.find()

To display the results in a more readable format in MongoDB Shell, use:

db.students.find().pretty()

Explanation: MongoDB returns all student documents stored in the students collection.

3. Find Documents by a Specific Field

You can pass a filter object to find() to retrieve documents matching a particular value.

Example 1: Find a Student by Name
db.students.find({
    name: "Rahul"
})
Example 2: Find Students by Course
db.students.find({
    course: "Python"
})
Example 3: Find Students by City
db.students.find({
    city: "Patna"
})

MongoDB returns every document that matches the supplied filter. If several students have the same course or city, all matching documents are returned.

4. Find One Document Using findOne()

The findOne() method returns one matching document. If no document matches, it returns null.

Example 1: Find Rahul
db.students.findOne({
    name: "Rahul"
})
Example 2: Find a Python Student
db.students.findOne({
    course: "Python"
})

If multiple documents match, findOne() returns one of them. Without a sort, you should not rely on which matching document it returns.

5. Find Documents Using Numeric Values

You can search for documents using numeric fields such as age, marks, fees, and salary.

Example 1: Find Students Aged 20
db.students.find({
    age: 20
})
Example 2: Find Students Aged 21
db.students.find({
    age: 21
})
Example 3: Find Students in a Particular City and Age
db.students.find({
    city: "Gaya",
    age: 22
})

When multiple fields are provided in the same filter, MongoDB requires all those field conditions to match.

6. Find Documents Using Multiple Conditions

By default, conditions placed together in a filter use AND logic.

Example 1: Python Students from Gaya
db.students.find({
    course: "Python",
    city: "Gaya"
})

The document must have both the specified course and city to match.

Example 2: Students Aged 20 from Patna
db.students.find({
    age: 20,
    city: "Patna"
})
Example 3: Find Students by Name and Course
db.students.find({
    name: "Neha",
    course: "Python"
})

7. Find Documents Using Comparison Operators

Comparison operators let you find documents using conditions such as greater than, less than, or equal to.

Example 1: Age Greater Than 20
db.students.find({
    age: { $gt: 20 }
})
Example 2: Age Less Than 22
db.students.find({
    age: { $lt: 22 }
})
Example 3: Age Greater Than or Equal to 21
db.students.find({
    age: { $gte: 21 }
})
Example 4: Age Not Equal to 20
db.students.find({
    age: { $ne: 20 }
})

These operators are useful for searching student marks, employee salaries, product prices, and other numeric data.

8. Display Selected Fields Using Projection

Projection allows you to select which fields should appear in the query results.

Example 1: Display Only Name and Course
db.students.find(
    {},
    { name: 1, course: 1 }
)

The _id field is included by default unless you explicitly exclude it.

Example 2: Exclude the _id Field
db.students.find(
    {},
    { _id: 0, name: 1, course: 1 }
)
Example 3: Display Only Student Names
db.students.find(
    {},
    { _id: 0, name: 1 }
)

Projection changes the fields displayed in the results; it does not delete other fields from stored documents.

9. Sort and Limit Search Results

Combine find() with sort() and limit() to control the order and number of returned documents.

Example 1: Sort by Age in Ascending Order
db.students.find().sort({
    age: 1
})
Example 2: Sort by Age in Descending Order
db.students.find().sort({
    age: -1
})
Example 3: Display Only Two Students
db.students.find().limit(2)
Example 4: Find Python Students and Sort by Age
db.students.find({
    course: "Python"
}).sort({
    age: 1
})

10. Check Whether a Document Exists

You can use findOne() to check whether a document matching a filter exists.

db.students.findOne({
    name: "Rahul"
})

If a matching document exists, MongoDB returns it. Otherwise, the result is null.

To count how many documents match a filter, use countDocuments().

db.students.countDocuments({
    course: "Python"
})

11. Common find() Patterns

Requirement Command
Find all documents db.students.find()
Find one document db.students.findOne()
Find by name db.students.find({ name: "Rahul" })
Find by course db.students.find({ course: "Python" })
Age greater than 20 db.students.find({ age: { $gt: 20 } })
Show selected fields db.students.find({}, { name: 1, course: 1 })
Sort by age db.students.find().sort({ age: 1 })
Limit results db.students.find().limit(2)
Count Python students db.students.countDocuments({ course: "Python" })

📝 Practical Assignment

Use the school database and the students collection created in this lesson. Write MongoDB commands to complete these tasks.

  1. Display all student documents.
  2. Find the student named Amit.
  3. Find all students enrolled in ADCA.
  4. Find all students from Patna.
  5. Find students whose age is greater than 20.
  6. Find students whose age is less than 22.
  7. Find Python students from Aurangabad.
  8. Display only the name and course fields.
  9. Sort students by age in descending order.
  10. Display only the first three student documents.
  11. Count all students enrolled in Python.

🧠 Quick Quiz

1. Which method retrieves all matching documents?


2. Which operator means greater than?


3. What does limit(2) do?