Paramclasses Academy - Blog

Tutorials Details

←
Post 12 of 35
→

MongoDB find() Query Tutorial: Search and Retrieve Documents

 MongoDB find() Query Tutorial: Search and Retrieve Documents

November 5, 2026

 

MongoDB find() Query Tutorial: Search and Retrieve Documents

Welcome to Param Classes!

In this tutorial, we will learn how to use the find() method in MongoDB to search and retrieve documents from a collection. The find() method is one of the most commonly used methods in MongoDB because it allows developers to retrieve specific records based on different conditions.

Whether you want to display all records, search for a particular student, filter data based on age, or retrieve documents with specific values, MongoDB provides a flexible query system to handle these operations.

Let's understand MongoDB find() with practical examples.

✦ 1. What is the find() Method in MongoDB?

The find() method is used to retrieve documents from a MongoDB collection.

It allows you to search for documents by providing a filter condition. If no filter is provided, MongoDB returns all documents from the collection.

Syntax:

db.collection_name.find()

Syntax with a condition:

db.collection_name.find({ field: value })

For example:

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

This query retrieves documents where the name field has the value "Rahul".

Important: The find() method returns a cursor. In MongoDB Shell (mongosh), the cursor is automatically iterated and its documents are displayed.

✦ 2. Create a Collection with Sample Data

Before using the find() method, let's insert some sample student records.

db.students.insertMany([
    {
        name: "Rahul",
        age: 22,
        course: "MongoDB",
        marks: 85,
        city: "Raipur"
    },
    {
        name: "Amit",
        age: 24,
        course: "Java",
        marks: 78,
        city: "Delhi"
    },
    {
        name: "Priya",
        age: 21,
        course: "MongoDB",
        marks: 92,
        city: "Mumbai"
    },
    {
        name: "Neha",
        age: 23,
        course: "Python",
        marks: 88,
        city: "Raipur"
    },
    {
        name: "Rohit",
        age: 20,
        course: "Java",
        marks: 70,
        city: "Bhopal"
    }
])

Now our students collection contains five student documents.

✦ 3. Retrieve All Documents Using find()

If you want to display all documents from a collection, use find() without a filter.

Example:

db.students.find({})

You can also write:

db.students.find()

Explanation:

  • db represents the current database.

  • students is the collection name.

  • find() retrieves documents.

  • {} is an empty filter, which matches all documents.

Result: All five student records will be displayed.

✦ 4. Search Documents Using a Specific Field

You can retrieve documents by matching a particular field and value.

Example:

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

Explanation:

This query searches for students whose name is Rahul.

Expected Result:

{
    name: "Rahul",
    age: 22,
    course: "MongoDB",
    marks: 85,
    city: "Raipur"
}

You can search using any existing field, such as name, age, course, marks, or city.

Example:

db.students.find({ city: "Raipur" })

This query retrieves all students whose city is Raipur.

✦ 5. MongoDB Comparison Operators

Comparison operators help you retrieve documents based on numerical or value-based conditions.

Some commonly used comparison operators are:

Operator Meaning
$gt Greater than
$gte Greater than or equal to
$lt Less than
$lte Less than or equal to
$ne Not equal to
$in Matches any value in an array
$nin Does not match any value in an array

Example 1: Greater Than ($gt)

Find students whose age is greater than 21.

db.students.find({
    age: { $gt: 21 }
})

Example 2: Greater Than or Equal To ($gte)

Find students whose marks are 85 or higher.

db.students.find({
    marks: { $gte: 85 }
})

Example 3: Less Than ($lt)

Find students whose age is less than 23.

db.students.find({
    age: { $lt: 23 }
})

Example 4: Less Than or Equal To ($lte)

Find students whose marks are 78 or lower.

db.students.find({
    marks: { $lte: 78 }
})

Example 5: Not Equal ($ne)

Find students whose course is not MongoDB.

db.students.find({
    course: { $ne: "MongoDB" }
})

Example 6: Match Multiple Values ($in)

Find students who belong to either Raipur or Mumbai.

db.students.find({
    city: { $in: ["Raipur", "Mumbai"] }
})

✦ 6. MongoDB Logical Operators

Logical operators allow you to combine multiple query conditions.

Common logical operators include:

  • $and

  • $or

  • $not

  • $nor

Example 1: AND Operator

Find students who are older than 21 and have marks greater than 80.

db.students.find({
    $and: [
        { age: { $gt: 21 } },
        { marks: { $gt: 80 } }
    ]
})

MongoDB also supports implicit AND when you provide multiple fields in the same filter.

db.students.find({
    age: { $gt: 21 },
    marks: { $gt: 80 }
})

Both examples require both conditions to match.

Example 2: OR Operator

Find students whose city is Raipur or whose course is Java.

db.students.find({
    $or: [
        { city: "Raipur" },
        { course: "Java" }
    ]
})

Example 3: NOT Operator

Find students whose age is not greater than 21.

db.students.find({
    age: { $not: { $gt: 21 } }
})

Example 4: NOR Operator

Find students who are neither from Raipur nor from Mumbai.

db.students.find({
    $nor: [
        { city: "Raipur" },
        { city: "Mumbai" }
    ]
})

✦ 7. MongoDB Projection – Select Specific Fields

Projection is used to retrieve only selected fields from documents instead of displaying every field.

Syntax:

db.collection_name.find(
    { filter_condition },
    { field_name: 1 }
)

Example 1: Display Only Name and Course

db.students.find(
    {},
    {
        name: 1,
        course: 1
    }
)

This query displays only the name and course fields, along with _id by default.

Example 2: Hide the _id Field

db.students.find(
    {},
    {
        name: 1,
        course: 1,
        _id: 0
    }
)

Now only the name and course fields will be displayed.

Example 3: Exclude a Specific Field

db.students.find(
    {},
    {
        city: 0
    }
)

This query returns all fields except city.

Important: In a projection, you generally cannot mix inclusion (1) and exclusion (0) for different fields. The _id field is the exception.

✦ 8. Sort Documents Using sort()

The sort() method is used to arrange retrieved documents in ascending or descending order.

Syntax:

db.collection_name.find().sort({ field_name: 1 })
  • 1 means ascending order.

  • -1 means descending order.

Example 1: Sort by Age in Ascending Order

db.students.find().sort({ age: 1 })

This displays students from the youngest to the oldest.

Example 2: Sort by Marks in Descending Order

db.students.find().sort({ marks: -1 })

This displays students from the highest marks to the lowest marks.

Example 3: Sort by Multiple Fields

db.students.find().sort({
    city: 1,
    age: -1
})

This sorts students by city in ascending order and then by age in descending order within each city.

✦ 9. Limit Documents Using limit()

The limit() method restricts the number of documents returned.

Syntax:

db.collection_name.find().limit(number)

Example:

db.students.find().limit(3)

This query returns a maximum of three documents.

Practical Example:

If your collection contains 1,000 student records and you want to display only the first five records, you can use:

db.students.find().limit(5)

✦ 10. Skip Documents Using skip()

The skip() method skips a specified number of documents before returning the remaining results.

Syntax:

db.collection_name.find().skip(number)

Example:

db.students.find().skip(2)

This skips the first two documents and returns the remaining documents.

Pagination Example

You can combine skip() and limit() to create pagination.

db.students.find()
    .skip(0)
    .limit(2)

This retrieves the first two documents.

For the next page:

db.students.find()
    .skip(2)
    .limit(2)

This skips the first two documents and retrieves the next two.

For consistent pagination, combine sorting with skip and limit:

db.students.find()
    .sort({ _id: 1 })
    .skip(0)
    .limit(2)

✦ 11. Difference Between find() and findOne()

MongoDB provides two commonly used methods to retrieve documents.

find() findOne()
Returns a cursor containing matching documents. Returns one matching document or null.
Can retrieve multiple documents. Retrieves at most one document.
Useful for displaying lists of records. Useful for retrieving a single record.

Example of find()

db.students.find({
    course: "MongoDB"
})

This retrieves all students whose course is MongoDB.

Example of findOne()

db.students.findOne({
    course: "MongoDB"
})

This retrieves only one matching student document.

Note: Without a sort condition, do not depend on findOne() returning a particular matching document.

✦ 12. Count Matching Documents Using countDocuments()

The countDocuments() method counts the number of documents that match a filter.

Example 1: Count All Students

db.students.countDocuments({})

This returns the total number of documents in the collection.

Example 2: Count MongoDB Students

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

This returns the number of students whose course is MongoDB.

Example 3: Count Students Older Than 21

db.students.countDocuments({
    age: { $gt: 21 }
})

✦ 13. Working with Nested Documents

MongoDB also supports searching inside nested documents using dot notation.

Consider this sample document:

{
    name: "Rahul",
    address: {
        city: "Raipur",
        state: "Chhattisgarh"
    }
}

To find students whose city is Raipur, use:

db.students.find({
    "address.city": "Raipur"
})

Dot notation allows you to access fields inside embedded documents.

✦ 14. Practical Example – Search Students Based on Different Conditions

Let's practice some common queries using our students collection.

Find students from Raipur:

db.students.find({
    city: "Raipur"
})

Find students with marks greater than 80:

db.students.find({
    marks: { $gt: 80 }
})

Find students enrolled in Java:

db.students.find({
    course: "Java"
})

Find students older than 20 and from Raipur:

db.students.find({
    age: { $gt: 20 },
    city: "Raipur"
})

Display only student names and marks:

db.students.find(
    {},
    {
        name: 1,
        marks: 1,
        _id: 0
    }
)

Display the top three students according to marks:

db.students.find()
    .sort({ marks: -1 })
    .limit(3)

✦ 15. Common Mistakes to Avoid

While using MongoDB find(), beginners sometimes make these mistakes:

  1. Incorrect collection name: Always check that the collection name is correct.

  2. Incorrect field name: MongoDB field names are case-sensitive. Name and name are different fields.

  3. Missing quotation marks: String values should be written inside quotation marks.

  4. Incorrect comparison operator: Use $gt, $lt, $gte, or $lte according to your requirement.

  5. Incorrect projection: Do not mix inclusion and exclusion in the same projection, except for _id.

  6. Unexpected results: Check the filter conditions and the actual data stored in the collection.

  7. Unsorted pagination: Use sort() with skip() and limit() when you need consistent page results.

✦ 16. Practical Exercise

Now it's your turn to practice MongoDB queries.

Use the students collection created in this tutorial and complete the following tasks:

  1. Display all student documents.

  2. Find the student named Priya.

  3. Find students whose age is greater than 22.

  4. Find students whose marks are less than 85.

  5. Find students who belong to Raipur or Mumbai.

  6. Display only student names and courses.

  7. Sort students by marks in descending order.

  8. Display only the first three students.

  9. Skip the first two records and display the next two.

  10. Count how many students are enrolled in MongoDB.

Try writing each query yourself before checking the examples above.

✦ 17. Conclusion

In this tutorial, we learned how to use the MongoDB find() method to search and retrieve documents from a collection.

We covered basic queries, comparison operators, logical operators, projection, sorting, limiting, skipping, counting documents, and nested document searches.

The find() method is an essential part of MongoDB because it helps developers retrieve the required data efficiently.

Keep practicing these queries to improve your MongoDB skills.

Keep Learning with Param Classes!

 

←
Post 12 of 35
→