Projections

You can give find and findOne an optional second argument, projections. The syntax is the same as MongoDB: { a: 1, b: 1 } to return only the a and b fields, { a: 0, b: 0 } to omit these two fields. You cannot use both modes at the time, except for _id which is by default always returned and which you can choose to omit. You can project on nested documents.

  1. // Same database as above
  2. // Keeping only the given fields
  3. db.find({ planet: 'Mars' }, { planet: 1, system: 1 }, function (err, docs) {
  4. // docs is [{ planet: 'Mars', system: 'solar', _id: 'id1' }]
  5. });
  6. // Keeping only the given fields but removing _id
  7. db.find({ planet: 'Mars' }, { planet: 1, system: 1, _id: 0 }, function (err, docs) {
  8. // docs is [{ planet: 'Mars', system: 'solar' }]
  9. });
  10. // Omitting only the given fields and removing _id
  11. db.find({ planet: 'Mars' }, { planet: 0, system: 0, _id: 0 }, function (err, docs) {
  12. // docs is [{ inhabited: false, satellites: ['Phobos', 'Deimos'] }]
  13. });
  14. // Failure: using both modes at the same time
  15. db.find({ planet: 'Mars' }, { planet: 0, system: 1 }, function (err, docs) {
  16. // err is the error message, docs is undefined
  17. });
  18. // You can also use it in a Cursor way but this syntax is not compatible with MongoDB
  19. db.find({ planet: 'Mars' }).projection({ planet: 1, system: 1 }).exec(function (err, docs) {
  20. // docs is [{ planet: 'Mars', system: 'solar', _id: 'id1' }]
  21. });
  22. // Project on a nested document
  23. db.findOne({ planet: 'Earth' }).projection({ planet: 1, 'humans.genders': 1 }).exec(function (err, doc) {
  24. // doc is { planet: 'Earth', _id: 'id2', humans: { genders: 2 } }
  25. });