Open In App

Mongoose Query select() Method

Last Updated : 25 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Mongoose is an Object Data Modeling (ODM) library for MongoDB that provides a straightforward way to interact with MongoDB databases using JavaScript. One of the key features of Mongoose is its ability to handle complex queries efficiently. The select() method in Mongoose plays an important role when it comes to specifying which fields to include or exclude when fetching documents from a MongoDB collection.

What is the Select() Method in Mongoose?

The select() method in Mongoose is used to specify which document fields to include or exclude from the result set when querying the database. This can be extremely helpful when we want to optimize performance by retrieving only the fields you need, rather than fetching the entire document. By default, Mongoose returns all fields, but the select() method allows us to control which fields are included or excluded.

  • Inclusion: Specify fields we want to retrieve.
  • Exclusion: Specify fields we want to exclude from the results.

Syntax:

Query.prototype.select()

Parameters:

  • arg: This can be a String, Object, or Array of Strings specifying the fields to include or exclude.
  • A String can be a space-separated list of fields, with a + or - prefix to include or exclude specific fields.
  • An Object with field names as keys and 1 for inclusion or 0 for exclusion.

Return Type:

  • The select() method returns a Query object, which can be used for further chaining or execution.

Creating a Node.js Application And Installing Mongoose

Before using the select() method, we need to set up your Node.js application and install Mongoose.

Step 1: Create a Node.js Application

To set up a new Node.js application, run the following commands:

mkdir folder_name
cd folder_name
npm init -y
touch main.js

Step 2: Install Mongoose

After creating the ReactJS application, Install the required module using the following command:

npm install mongoose

Step 3: Check Mongoose Version

To check if Mongoose is installed correctly, run:

npm version mongoose

Project Structure: It will look like the following.

 


GUI Representation of the  Database using MongoDB Compass: Currently, the collection has no data.

 


How to Use the select() Method in Mongoose

Let’s look at some practical examples to better understand how to use the select() method in Mongoose.

Example 1: Deselecting a Field

In this example, we will use the Query API select() method to deselect the "age" property from the documents fetched from DB.

Filename: main.js

const mongoose = require('mongoose')

// Database connection
mongoose.connect('mongodb://localhost:27017/query-helpers', {
dbName: 'event_db',
useNewUrlParser: true,
useUnifiedTopology: true
}, err => err ? console.log(err) : console.log('Connected to database'));

const personSchema = new mongoose.Schema({
name: {
type: String,
},
age: {
type: Number,
}
});

const personsArray = [
{
name: 'Luffy',
age: 22
},
{
name: 'Nami',
age: 30
},
{
name: 'Zoro',
age: 15
}
]

const Person = mongoose.model('Person', personSchema);

(async () => {
await Person.insertMany(personsArray);
const query = Person.find().select('-age')
const persons = await query;
console.log(persons);
})()

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

node main.js

Output: We see that the value remains unchanged in the result.

GUI Representation of the Database using MongoDB Compass:

Example 2: Overriding Schema Default Field Selection

In this example, we will first set the select option to false in the schema definition for the name field but override this using the select() method in the query.

Filename: main.js

const mongoose = require('mongoose')

// Database connection
mongoose.connect('mongodb://localhost:27017/query-helpers', {
dbName: 'event_db',
useNewUrlParser: true,
useUnifiedTopology: true
}, err => err ? console.log(err)
: console.log('Connected to database'));

const personSchema = new mongoose.Schema({
name: {
type: String,
select: false
},
age: {
type: Number,
}
});

const personsArray = [
{
name: 'Luffy',
age: 22
},
{
name: 'Nami',
age: 30
},
{
name: 'Zoro',
age: 15
}
]

const Person = mongoose.model('Person', personSchema);

(async () => {
await Person.insertMany(personsArray);
const query = Person.find().select('name')
const persons = await query;
console.log(persons);
})()

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

node main.js

Output: We see that the value remains unchanged in the result.

GUI Representation of the  Database using MongoDB Compass:

Conclusion

The select() method in Mongoose is an essential tool for controlling which fields are retrieved when querying a MongoDB database. By using this method, we can optimize performance, reduce the size of the result set, and tailor the query to our needs. Whether you're excluding sensitive data or just optimizing your queries, the select() method provides the flexibility to fine-tune your database interactions. Understanding and utilizing select() can significantly improve the efficiency of your MongoDB queries and streamline your application’s data handling.


Next Article

Similar Reads