Mongoose Query select() Method
Last Updated :
25 Mar, 2025
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.
Similar Reads
Mongoose prototype.$set() Method
In Mongoose, the prototype.$set() method is a crucial function that allows developers to update specific fields of a document in a MongoDB collection. This method enables atomic modification of field values within a document, offering precise control over your MongoDB data. This article explains how
5 min read
Mongoose Populate() Method
The populate() method in Mongoose is used to automatically replace a field in a document with the actual data from a related document. It simplifies handling referenced documents and helps replace ObjectIds with the actual data from related collections. This article explores the Mongoose populate()
5 min read
Mongoose Query getFilter() Method
The getFilter() method in Mongoose is a powerful tool used to retrieve the current query filter applied to a query in the Mongoose query system. This method is essential for developers who need to examine or manipulate the query criteria before executing the query. In this article, we will explain t
5 min read
Mongoose Schema.prototype.pre() Method
The Mongoose Schema API pre() method is used to add a pre-hook to the mongoose Schema methods and can be used to perform pre Schema method operations. In this article, we will explain the Mongoose Schema.prototype.pre() method, explaining how to use it effectively for pre-operation hooks in your Mon
4 min read
Mongoose Query prototype.selected() API
Mongoose is an Object Data Modeling (ODM) library for MongoDB. It defines a strongly-typed schema, with default values and schema validations which are later mapped to a MongoDB document. Mongoose Query API selected method is used to determine whether any selection is made in the Mongoose Query. It
3 min read
Mongoose Query() Function
The Query constructor is used for building the queries. So the user does not need to instantiate a Query directly. The `query` is an instance of `Query`. Syntax: Query() Parameters: This function has optional parameters like model, condition, collection and options. Return Value: This function re
2 min read
updateMany() Method in Mongoose
In Mongoose, the updateMany() method is a powerful tool for performing bulk updates in MongoDB. It updates multiple documents that match a specified condition, applying the changes to all the matched documents in a single operation. Unlike updateOne(), which updates only the first matching document,
4 min read
Mongoose Schemas Query Helpers
Mongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose Schema Query Helpers are like instance methods for Mongoose queries. These query helpers can be used to filter out mongoose query results or perform additional operations on the existing result. Creating node appl
3 min read
Mongoose Schema.prototype.static() Method
Mongoose is an essential Object Data Modeling (ODM) library for MongoDB in Node.js. It provides powerful tools to interact with MongoDB using a well-defined schema structure. One of the most useful features of Mongoose is its ability to define static methods on schemas, which allows us to perform cl
5 min read
Mongoose Query() API
The Mongoose API Query() method of the Mongoose API is used as a constructor to create a reference of Query. It allows us to create query objects and build query expressions. We do not need to create an object of the Query class in order to interact with the MongoDB collection. We can directly call
3 min read