How to use MongoDB Projection in Mongoose?
Last Updated :
27 Jun, 2024
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:
Project StructureThe 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.
Similar Reads
How to Use MongoDB and Mongoose with Node.js ?
MongoDB is a popular NoSQL database that offers flexibility and scalability, making it an excellent choice for modern applications. Mongoose, a powerful ODM (Object Data Modeling) library, simplifies the interaction between MongoDB and Node.js by providing a schema-based solution for data validation
6 min read
How to Post Data in MongoDB Using NodeJS?
In this tutorial, we will go through the process of creating a simple Node.js application that allows us to post data to a MongoDB database. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. And also we use the Ejs for our front end to render the simple
5 min read
How to do a Full-Text Search in MongoDB using Mongoose
In MongoDB, performing a full-text search allows us to query and retrieve documents based on textual content matching certain criteria. When using Mongoose, an ODM (Object Data Modeling) library for MongoDB in Node.js, conducting full-text search operations can be efficiently achieved using the Mong
5 min read
Mongoose Query.prototype.projection() API
The Mongoose Query API.prototype.projection() method of the Mongoose API is used on the Query objects. It allows us to set and configure the projection for the query objects. Using this method we can get the existing projection details and also we can remove the existing projection. Let us understan
3 min read
How does Query.prototype.mod() work in Mongoose?
The Query.prototype.mod() function is used to specify a $mod condition. This function basically filters documents for documents whose path property is a number that is equal to remainder modulo divisor. Syntax:  Query.prototype.mod() Parameters: This function has one optional path parameter and an
2 min read
How to Connect Node.js To MongoDB Atlas Using Mongoose?
MongoDB Atlas is a cloud-based database service that offers robust features and scalability for managing our data. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. And also we use the Ejs for our front end to render the simple HTML form. In this tutoria
6 min read
How to Join two Schemas in Mongoose?
Mongoose is a popular MongoDB object modeling tool for Node.js that simplifies data manipulation. However, developers often face challenges when trying to join two schemas in Mongoose, as MongoDB, a NoSQL database, does not natively support join operations like SQL databases. In this article, We wil
5 min read
Mongoose Query.prototype.mod() API
The Mongoose Query API.prototype.mod() method of the Mongoose API is used on the Query objects. It allows us to provide condition in the form of modulus. Using this method we can select the documents where the value of the field divided by a divisor has the specified remainder. Let us understand mod
3 min read
How to Perform Find Operation With Projection in MongoDB Using NodeJS?
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
5 min read
How to Handle Errors in MongoDB Operations using NodeJS?
Handling errors in MongoDB operations is important for maintaining the stability and reliability of our Node.js application. Whether we're working with CRUD operations, establishing database connections, or executing complex queries, unexpected errors can arise. Without proper error handling, these
8 min read