How to Perform Find Operation With Projection in MongoDB Using NodeJS?

Last Updated : 16 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

MongoDB's find() method can be used to query the documents from the collection. Protection in MongoDB allows you to select the fields to return in the query results which can be useful for improving the performance and reducing the amount of the data transferred over the network.

In this article, we will guide you how to perform the find operation with projection using Node.js. with different approaches.

These are the following approaches:

Inserting the Sample Data

Before we can proceed with the approaches, let's insert some sample data into the MongoDB collection.

JavaScript
//server.js

const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);

async function insertSampleData() {
    try {
        await client.connect();
        const database = client.db('exampleDB');
        const collection = database.collection('exampleCollection');

        const sampleData = [
            { name: 'John Doe', age: 30, city: 'New York' },
            { name: 'Jane Smith', age: 27, city: 'Los Angeles' },
            { name: 'Alice Johnson', age: 35, city: 'Chicago' },
            { name: 'Mike Davis', age: 40, city: 'Houston' }
        ];

        await collection.insertMany(sampleData);
        console.log('Sample data inserted');
    } finally {
        await client.close();
    }
}

insertSampleData().catch(console.dir);

Output

insert
Inserting the Sample Data

Approach 1: Using Find Method With Projection

This approach directly specifies the fields to be included in the result using the projection object as the second parameter of the find method. The projection object can determines which fields should be included (1) or excluded (0) from the documents that match the query criteria.

Detailed Steps:

  1. Connect to MongoDB database: We can use MongClient to connect to the MongoDB server.
  2. Specify the query criteria: Define the conditions that the documents must meet to be included into the result set.
  3. Specify the projection fields: Define which fields to include or the exclude in result set using projection object.
  4. Execute the find method: We can use find method with the query and projection objects to retrieve the documents.
  5. Convert the result to an array: We can use the toArray method to convert the cursor to the array of the documents.

Example: We are using Find method with projection to fetch the specific data.

JavaScript
//server.js

const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);

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

        const query = { age: { $gte: 25 } };
        const options = { fields: { name: 1, age: 1 } };

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

run().catch(console.dir);

Output

approach1
find method with projection

Approach 2: Using Find Method With Project Method

This approach can be used to chain the project method to find method for specifying the fields to include in the result. This project method is called on the cursor by find method and it can allowing you define the projection separately.

Detailed Steps:

  1. Connect to MongoDB database: We can use MongoClient to connect to the MongoDB server.
  2. Specify the query method: Define the condition that the documents must meet to be included in result set.
  3. Execute the find method: We can use the find method with the query object to retrieve the documents.
  4. Specify the projection fields: We can call the project method on the cursor returned by the find method to define which fields to include or exclude in the result set.
  5. Convert the result to an array: We can use the toArray method to convert the cursor to the array of documents.

Example: In this we are using Find with project method to fetch the data.

JavaScript
//server.js

const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);

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

        const query = { age: { $gte: 30 } };

        const docs = 
        await collection.find(query).project({ name: 1, age: 1 }).toArray();
        console.log(docs);
    } finally {
        await client.close();
    }
}

run().catch(console.dir);

Output

approach2
Find Method With Project Method

Approach 3: Using Find Method With Options Object

This approach can be uses the options object to specify the fields to the include or exclude in the result set. The options object contains the fields properly which can defines the projection fields.

Detailed Steps:

  1. Connect to MongoDB database: We can use the MongoClient to connect to the MongoDB server.
  2. Specify the query criteria: Define the conditions that the documents must meet to be included in result set.
  3. Specify the projection fields: Define the fields to include or exclude in result set using the fields properly of the options object.
  4. Execute the find method: We can use the find method with query and options objects to retrieve the documents.
  5. Convert the result to an array: We can use the toArray method to convert the cursor to the array of the documents.

Example: In this example we are usingFind with options objec

JavaScript
//server.js

const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);

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

        const query = { age: { $gte: 30 } };
        const options = { fields: { name: 1, age: 1 } };

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

run().catch(console.dir);

Output

approach3
Find Method With Options Objec

Next Article

Similar Reads