0
0
MongodbHow-ToBeginner · 4 min read

How to Use Select in Mongoose: Syntax and Examples

In Mongoose, use the select() method on a query to specify which fields to include or exclude in the result. Pass a string with field names separated by spaces, prefixing with - to exclude fields, or use an object with field names as keys and 1 or 0 as values.
📐

Syntax

The select() method lets you choose which fields to return from a query. You can use it in two ways:

  • String syntax: Pass a space-separated string of field names. Prefix a field with - to exclude it.
  • Object syntax: Pass an object where keys are field names and values are 1 (include) or 0 (exclude).
javascript
Model.find().select('field1 field2 -field3')
// or
Model.find().select({ field1: 1, field2: 1, field3: 0 })
💻

Example

This example shows how to find all users but only return their name and email fields, excluding the password field.

javascript
const mongoose = require('mongoose');

// Define a simple User schema
const userSchema = new mongoose.Schema({
  name: String,
  email: String,
  password: String
});

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

async function run() {
  await mongoose.connect('mongodb://localhost:27017/testdb');

  // Create a sample user
  await User.create({ name: 'Alice', email: 'alice@example.com', password: 'secret123' });

  // Find users selecting only name and email, excluding password
  const users = await User.find().select('name email -password');
  console.log(users);

  await mongoose.disconnect();
}

run();
Output
[ { _id: <ObjectId>, name: 'Alice', email: 'alice@example.com' } ]
⚠️

Common Pitfalls

Common mistakes when using select() include:

  • Mixing inclusion and exclusion fields in the same query (except for _id).
  • Forgetting that select() only affects the fields returned, not the query conditions.
  • Using incorrect field names or typos, which silently return empty or unexpected results.

Example of wrong and right usage:

javascript
// Wrong: mixing inclusion and exclusion
Model.find().select('name -email'); // This will cause an error

// Right: only inclusion or only exclusion
Model.find().select('name email');
Model.find().select('-password');
📊

Quick Reference

UsageDescriptionExample
Include fieldsReturn only specified fieldsselect('name email')
Exclude fieldsExclude specified fieldsselect('-password')
Object syntaxUse object to include/excludeselect({ name: 1, password: 0 })
Default _idReturned unless excluded explicitlyselect('-_id')
Mixing fieldsDo not mix include and exclude except _idselect('name -email') // wrong

Key Takeaways

Use select() to specify which fields to include or exclude in Mongoose query results.
Pass a space-separated string or an object with field names and 1/0 values to select().
Do not mix inclusion and exclusion fields in the same select() call except for _id.
By default, _id is included unless explicitly excluded.
Check field names carefully to avoid silent errors or empty results.