MongoDB - Getting StartedMongoDB - Getting Started1

Read Operations in MongoDB



Read Operations in MongoDB

Read operations allow you to retrieve data stored in MongoDB collections. The two most commonly used functions for this purpose are find() and findOne().

MongoDB queries are performed on collections using filter objects that specify the criteria for matching documents.

find() vs findOne()

Step 1: Insert Sample Data

Let’s create a students collection with multiple documents.


    db.students.insertMany([
      { name: "Alice", age: 22, grade: "A", subjects: ["Math", "Physics"] },
      { name: "Bob", age: 24, grade: "B", subjects: ["English", "History"] },
      { name: "Charlie", age: 22, grade: "A", subjects: ["Biology", "Chemistry"] },
      { name: "David", age: 23, grade: "C", subjects: ["Math", "English"] }
    ]);
    

Output:

    {
      acknowledged: true,
      insertedIds: { ...ObjectIds... }
    }
    

Step 2: Retrieve All Documents

Use find() with an empty filter {} to fetch all documents.


    db.students.find({});
    

Output:

    { _id: ..., name: "Alice", age: 22, grade: "A", subjects: [ "Math", "Physics" ] }
    { _id: ..., name: "Bob", age: 24, grade: "B", subjects: [ "English", "History" ] }
    { _id: ..., name: "Charlie", age: 22, grade: "A", subjects: [ "Biology", "Chemistry" ] }
    { _id: ..., name: "David", age: 23, grade: "C", subjects: [ "Math", "English" ] }
    

This returns a cursor. In the MongoDB shell, results are printed directly. In code (Node.js or Python), you need to iterate over the cursor.

Step 3: Filtering Documents

Let’s filter documents where grade is "A".


    db.students.find({ grade: "A" });
    

Output:

    { _id: ..., name: "Alice", age: 22, grade: "A", subjects: [ "Math", "Physics" ] }
    { _id: ..., name: "Charlie", age: 22, grade: "A", subjects: [ "Biology", "Chemistry" ] }
    

Q: How does MongoDB know which documents to return?
A: It compares each document's grade field to "A" and returns matches. If no document matches, it returns an empty result.

Step 4: Use findOne() to Get a Single Document


    db.students.findOne({ age: 22 });
    

Output:

    { _id: ..., name: "Alice", age: 22, grade: "A", subjects: [ "Math", "Physics" ] }
    

Even though two students are aged 22, findOne() returns only the first match.

Step 5: Use Comparison Operators

Get students older than 22 using the $gt operator.


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

Output:

    { _id: ..., name: "Bob", age: 24, grade: "B", subjects: [ "English", "History" ] }
    { _id: ..., name: "David", age: 23, grade: "C", subjects: [ "Math", "English" ] }
    

Step 6: Projecting Specific Fields

You can limit the fields returned using projection. For example, get only name and grade:


    db.students.find({ grade: "A" }, { name: 1, grade: 1, _id: 0 });
    

Output:

    { name: "Alice", grade: "A" }
    { name: "Charlie", grade: "A" }
    

We used _id: 0 to exclude the default _id field.

Step 7: Combining Multiple Conditions

Let’s find students who are aged 22 and have grade "A".


    db.students.find({ age: 22, grade: "A" });
    

Output:

    { _id: ..., name: "Alice", age: 22, grade: "A", subjects: [ "Math", "Physics" ] }
    { _id: ..., name: "Charlie", age: 22, grade: "A", subjects: [ "Biology", "Chemistry" ] }
    

Step 8: Querying Arrays

Find students who have "Math" in their subjects.


    db.students.find({ subjects: "Math" });
    

Output:

    { _id: ..., name: "Alice", ... }
    { _id: ..., name: "David", ... }
    

MongoDB automatically checks if "Math" exists in the array field subjects.

Summary

Mastering find() and findOne() is essential to efficiently retrieving and understanding your data in MongoDB.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M