Trusted answers to developer questions

What is select() in Mongoose?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

select() is a method of Mongoose that is used to select document fields that are to be returned in the query result. It is used to include or exclude document fields that are returned from a Mongoose query. The select() method performs what is called query projection.

Example

query.select("a b");

The example above is a query to return fields a and b only.

MongoDB includes the _id field by default, so it cannot be excluded.

How to include a field with select()

When a field does not have the - prefix, then it is included. A + prefix means a forceful inclusion of the field.

Including a field could also be done by using 1 through object notation. Including a field can be done as shown below:

// return only fields a and b
query.select("a b")

// same as the one above
query.select({a: 1, b: 1})

Example

Let’s see an example. In the example below, only the user’s name and age are returned from the query, while the password field is excluded.

// Create a schema
const user = new Schema({
name : String,
age: Number,
password: String
});
// Returns only "name" and "age" field
// and excludes "password" field
query.select("name age")
query.select({age: 1, name: 1})

How to exclude a field with select()

Excluding a field is done by prefixing the field with a -. Or we can use object notation and give the field a 0. Either of the two ways ensures that a field is not returned or is excluded from the query result.

Example

In the example below, the password field is excluded in the query result using the - or the object notation of 0.

// Create a schema
const user = new Schema({
name : String,
age: Number,
password: String
});
// Returns only "name" and "age" field
// and excludes "password" field
query.select("-password")
query.select({password: 0})

RELATED TAGS

mongoose
mongodb
query
projection

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
Did you find this helpful?