Sikau

MongoDB · Day 3 · about 25 min

Projection, sorting and counting

Choose fields, order and page results.

Send only what's needed

Documents can be big. Projection returns only the fields a screen needs; sort, skip and limit give you ordered pages; countDocuments and distinct answer quick questions.

find(filter, projection).sort().limit()

printjson(db.dishes.find({}, { name: 1, price: 1, _id: 0 }).sort({ price: -1 }).limit(3).toArray());

printjson(db.dishes.find({ category: "starter" }, { ingredients: 0, ratings: 0, _id: 0 }).toArray());

print(db.dishes.countDocuments({ veg: true }));
print(db.dishes.distinct("category"));

const page = 2, perPage = 3;
printjson(db.dishes.find({}, { name: 1, _id: 0 }).sort({ name: 1 }).skip((page - 1) * perPage).limit(perPage).toArray());

The rest of this lesson

  • Projection rulesexplain
  • Paging wellexplain
  • Which comes first?predict
  • Mixed projectionpredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 15 lessons of MongoDB