Open In App

How to use MongoDB Projection in Mongoose?

Last Updated : 27 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

MongoDB projection in Mongoose allows you to specify which fields to include or exclude in query results, optimizing data retrieval by returning only the necessary information from the database.

Prerequisites:

There are several ways to specify projection in Mongoose:

Steps to Setup the Application

Step 1: Initialize a New Node.js Folder

mkdir myapp

Step 2: Navigate to the project directory

cd myapp

Step 3: Initialize the NodeJS Project

npm init -y

Step 3: Install the necessary packages/libraries in your project using the following commands.

npm install mongoose
npm install mongodb

Project Structure:

Screenshot-2024-06-10-041854
Project Structure

The updated dependencies in package.json file will look like:

"dependencies": {
"mongoose": "^6.0.0",
"mongodb": "^4.0.0"
}

Using Strings to Include Fields

The simplest way to use projection is by passing a space-separated string of field names to the `.select()` method.

Model.find({}, 'field1 field2', (err, docs) => {
// docs contains field1 and field2 only
});

Using Objects to Include or Exclude Fields

You can also use an object to specify which fields to include or exclude. Including a field is indicated with a value of `1`, and excluding a field is indicated with a value of `0`.

Model.find({}, { field1: 1, field2: 1 }, (err, docs) => {
// docs contains field1 and field2 only
});
Model.find({}, { field1: 0, field2: 0 }, (err, docs) => {
// docs contains all fields except field1 and field2
});

Combining Include and Exclude Operations

Generally, you should either include or exclude fields, but not both. However, there is an exception when you want to exclude the `_id` field while including other fields.

Model.find({}, { field1: 1, field2: 1, _id: 0 }, (err, docs) => {
// docs contains field1 and field2 only, excluding _id
});

Example: Implementation to set up a simple Mongoose model.

Node
// index.js

const mongoose = require('mongoose');
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/test');
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
    console.log('Connected to MongoDB');
});

// Define a schema and model
const schema = new mongoose.Schema({
    name: String,
    age: Number,
    city: String
});

const User = mongoose.model('User', schema);

// Function to demonstrate projection
async function demonstrateProjection() {
    // Create some users
    await User.create([
        { name: 'Alice', age: 25, city: 'New York' },
        { name: 'Bob', age: 30, city: 'San Francisco' },
        { name: 'Charlie', age: 35, city: 'Los Angeles' }
    ]);

    // Using string projection
    const users1 = await User.find().select('name age');
    console.log('Projection using strings:', users1);

    // Using object projection (include)
    const users2 = await User.find().select({ name: 1, city: 1 });
    console.log('Projection using objects (include):', users2);


    // Using object projection (exclude)
    const users3 = await User.find().select({ age: 0 });
    console.log('Projection using objects (exclude):', users3);
}

demonstrateProjection().then(() => {
    mongoose.connection.close();
});

Step to Run Application: Run the application using the following command from the root directory of the project

node index.js
Connected to MongoDB
Projection using strings: [
{
_id: new ObjectId('6657878a09b52c9bc258f278'),
name: 'Bob',
age: 30
},
{
_id: new ObjectId('6657878a09b52c9bc258f277'),
name: 'Alice',
age: 25
},
{
_id: new ObjectId('6657878a09b52c9bc258f279'),
name: 'Charlie',
age: 35
}
]
Projection using objects (include): [
{
_id: new ObjectId('6657878a09b52c9bc258f278'),
name: 'Bob',
city: 'San Francisco'
},
{
_id: new ObjectId('6657878a09b52c9bc258f277'),
name: 'Alice',
city: 'New York'
},
{
_id: new ObjectId('6657878a09b52c9bc258f279'),
name: 'Charlie',
city: 'Los Angeles'
}
]
Projection using objects (exclude): [
{
_id: new ObjectId('6657878a09b52c9bc258f278'),
name: 'Bob',
city: 'San Francisco',
__v: 0
},
{
_id: new ObjectId('6657878a09b52c9bc258f277'),
name: 'Alice',
city: 'New York',
__v: 0
},
{
_id: new ObjectId('6657878a09b52c9bc258f279'),
name: 'Charlie',
city: 'Los Angeles',
__v: 0
}
]

Conclusion

Projection in Mongoose allows you to optimize your queries by selecting only the necessary fields from your MongoDB documents. This reduces data transfer and can significantly improve performance. With the select method, you can easily include or exclude fields as needed in your queries. For more advanced querying capabilities, refer to the Mongoose documentation.


Next Article

Similar Reads