Sorting and Limiting
Sorting orders the documents a find returns, and limiting caps how many come back. Both are chained onto the find call.
Alphabetical order
Titles sort from A to Z.
await Note.find().sort({ title: 1 });Highest first
Priorities sort from largest to smallest.
await Note.find().sort({ priority: -1 });Only two results
The limit keeps the first two titles in order.
await Note.find().sort({ title: 1 }).limit(2);Example
import mongoose from 'mongoose';
const noteSchema = new mongoose.Schema({
title: String,
done: Boolean,
priority: Number
});
const Note = mongoose.model('Note', noteSchema);
await mongoose.connect('mongodb://localhost:27017/notes');
await Note.create([
{ title: 'Buy milk', done: false, priority: 1 },
{ title: 'Ship MERN', done: true, priority: 3 },
{ title: 'Read a book', done: false, priority: 2 }
]);
const firstTwo = await Note.find().sort({ title: 1 }).limit(2);
console.log(firstTwo.map(n => n.title));
const topPriority = await Note.find().sort({ priority: -1 }).limit(1);
console.log(topPriority.map(n => n.title));
await mongoose.disconnect();Key points
- sort takes an object that names a field and a direction.
- A direction of 1 sorts smallest first, and -1 sorts largest first.
- limit takes a number and returns at most that many documents.
- Sort runs before limit, so the limit keeps the first results in order.
- Chaining keeps the query readable, one step at a time.
In this example, three notes are saved first. The first query sorts by title and limits the result to two notes. The second query sorts by priority from highest to lowest. It limits the result to one note, so the top priority note is printed.
Note
Sorting by a text field orders it alphabetically.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which query returns the two notes with the lowest priority values?