Sorting and paginating

If you don't specify a callback to find, findOne or count, a Cursor object is returned. You can modify the cursor with sort, skip and limit and then execute it with exec(callback).

  1. // Let's say the database contains these 4 documents
  2. // doc1 = { _id: 'id1', planet: 'Mars', system: 'solar', inhabited: false, satellites: ['Phobos', 'Deimos'] }
  3. // doc2 = { _id: 'id2', planet: 'Earth', system: 'solar', inhabited: true, humans: { genders: 2, eyes: true } }
  4. // doc3 = { _id: 'id3', planet: 'Jupiter', system: 'solar', inhabited: false }
  5. // doc4 = { _id: 'id4', planet: 'Omicron Persei 8', system: 'futurama', inhabited: true, humans: { genders: 7 } }
  6. // No query used means all results are returned (before the Cursor modifiers)
  7. db.find({}).sort({ planet: 1 }).skip(1).limit(2).exec(function (err, docs) {
  8. // docs is [doc3, doc1]
  9. });
  10. // You can sort in reverse order like this
  11. db.find({ system: 'solar' }).sort({ planet: -1 }).exec(function (err, docs) {
  12. // docs is [doc1, doc3, doc2]
  13. });
  14. // You can sort on one field, then another, and so on like this:
  15. db.find({}).sort({ firstField: 1, secondField: -1 }) ... // You understand how this works!