In this section, we will cover how to read documents from a MongoDB collection. Reading documents is a fundamental operation in MongoDB, allowing you to retrieve and display data stored in your database.

Key Concepts

  1. Find Operation: The primary method to read documents.
  2. Query Filters: Criteria to select specific documents.
  3. Projection: Selecting specific fields to return.
  4. Cursor: Handling large sets of data.
  5. Sorting: Ordering the results.
  6. Limiting and Skipping: Controlling the number of documents returned.

  1. Find Operation

The find method is used to retrieve documents from a collection. By default, it returns all documents in the collection.

Example

// Connect to the MongoDB client
const { MongoClient } = require('mongodb');
const uri = "your_mongodb_connection_string";
const client = new MongoClient(uri);

async function run() {
    try {
        await client.connect();
        const database = client.db('sample_database');
        const collection = database.collection('sample_collection');

        // Find all documents
        const documents = await collection.find().toArray();
        console.log(documents);
    } finally {
        await client.close();
    }
}

run().catch(console.dir);

Explanation

  • MongoClient: Connects to the MongoDB server.
  • database: Selects the database.
  • collection: Selects the collection.
  • find(): Retrieves all documents.
  • toArray(): Converts the cursor to an array.

  1. Query Filters

You can specify criteria to filter the documents returned by the find method.

Example

// Find documents with a specific field value
const query = { age: { $gt: 25 } }; // Find documents where age is greater than 25
const documents = await collection.find(query).toArray();
console.log(documents);

Explanation

  • query: Defines the filter criteria.
  • $gt: A query operator that stands for "greater than".

  1. Projection

Projection allows you to specify which fields to include or exclude in the returned documents.

Example

// Find documents and project specific fields
const query = { age: { $gt: 25 } };
const options = {
    projection: { _id: 0, name: 1, age: 1 } // Include 'name' and 'age', exclude '_id'
};
const documents = await collection.find(query, options).toArray();
console.log(documents);

Explanation

  • options: Contains the projection settings.
  • projection: Specifies fields to include (1) or exclude (0).

  1. Cursor

A cursor is an object that allows you to iterate over the results of a query.

Example

// Using a cursor to iterate over documents
const cursor = collection.find(query);
await cursor.forEach(doc => console.log(doc));

Explanation

  • cursor: Represents the result set of a query.
  • forEach: Iterates over each document in the cursor.

  1. Sorting

You can sort the results of a query using the sort method.

Example

// Sort documents by age in descending order
const query = { age: { $gt: 25 } };
const options = {
    sort: { age: -1 } // -1 for descending, 1 for ascending
};
const documents = await collection.find(query, options).toArray();
console.log(documents);

Explanation

  • sort: Specifies the sort order for the results.

  1. Limiting and Skipping

You can limit the number of documents returned and skip a certain number of documents.

Example

// Limit and skip documents
const query = { age: { $gt: 25 } };
const options = {
    limit: 5, // Limit to 5 documents
    skip: 2   // Skip the first 2 documents
};
const documents = await collection.find(query, options).toArray();
console.log(documents);

Explanation

  • limit: Restricts the number of documents returned.
  • skip: Skips a specified number of documents.

Practical Exercise

Task

Write a script to find all documents in a collection where the status field is "active", sort them by createdAt in ascending order, and project only the name and status fields.

Solution

const { MongoClient } = require('mongodb');
const uri = "your_mongodb_connection_string";
const client = new MongoClient(uri);

async function run() {
    try {
        await client.connect();
        const database = client.db('sample_database');
        const collection = database.collection('sample_collection');

        const query = { status: "active" };
        const options = {
            sort: { createdAt: 1 },
            projection: { _id: 0, name: 1, status: 1 }
        };

        const documents = await collection.find(query, options).toArray();
        console.log(documents);
    } finally {
        await client.close();
    }
}

run().catch(console.dir);

Explanation

  • query: Filters documents where status is "active".
  • sort: Sorts by createdAt in ascending order.
  • projection: Includes name and status fields, excludes _id.

Common Mistakes and Tips

  • Forgetting to close the client: Always ensure the MongoDB client is closed after operations to avoid memory leaks.
  • Incorrect query syntax: Ensure the query object is correctly formatted.
  • Projection errors: Remember that you cannot mix inclusion and exclusion in projections (except for _id).

Conclusion

In this section, you learned how to read documents from a MongoDB collection using various techniques such as filtering, projection, sorting, and pagination. These skills are essential for efficiently retrieving and displaying data from your MongoDB database. In the next section, we will cover how to update documents in MongoDB.

© Copyright 2024. All rights reserved