Query.prototype.select()

Parameters
  • arg «Object|String|Array<String>»
Returns:
  • «Query» this

Specifies which document fields to include or exclude (also known as the query “projection”)

When using string syntax, prefixing a path with - will flag that path as excluded. When a path does not have the - prefix, it is included. Lastly, if a path is prefixed with +, it forces inclusion of the path, which is useful for paths excluded at the schema level.

A projection must be either inclusive or exclusive. In other words, you must either list the fields to include (which excludes all others), or list the fields to exclude (which implies all other fields are included). The _id field is the only exception because MongoDB includes it by default.

Example

  1. // include a and b, exclude other fields
  2. query.select('a b');
  3. // Equivalent syntaxes:
  4. query.select(['a', 'b']);
  5. query.select({ a: 1, b: 1 });
  6. // exclude c and d, include other fields
  7. query.select('-c -d');
  8. // Use `+` to override schema-level `select: false` without making the
  9. // projection inclusive.
  10. const schema = new Schema({
  11. foo: { type: String, select: false },
  12. bar: String
  13. });
  14. // ...
  15. query.select('+foo'); // Override foo's `select: false` without excluding `bar`
  16. // or you may use object notation, useful when
  17. // you have keys already prefixed with a "-"
  18. query.select({ a: 1, b: 1 });
  19. query.select({ c: 0, d: 0 });