๐ $sort and $limit
๐น $sort โ Sorting resultsโ
Syntaxโ
{
$sort: {
field: 1,
}
}
{ field: 1 }
โ Ascending order (A โ Z, smallest to largest){ field: -1 }
โ Descending order (Z โ A, largest to smallest)- You can sort by multiple fields, just like SQL.
Example: Find the most recent reviews on our app.โ
db.reviews.aggregate([
{
$sort: { timestamp: -1 },
},
]);
Equivalent SQL queryโ
SELECT * FROM books ORDER BY timestamp DESC;
๐น $limit โ Limiting the number of resultsโ
Syntaxโ
{
$limit: n
}
- n is the maximum number of documents you want in your results.
Example: Find the 5 most recent reviews on our appโ
db.reviews.aggregate([
{
$sort: { timestamp: -1 },
},
{
$limit: 5,
},
]);
Equivalent SQL queryโ
SELECT * FROM books ORDER BY timestamp DESC LIMIT 5;
๐ Challengeโ
๐ 1. After the year 2000, which book has the most number of authors?โ
Answer
There are 2 ways to solve this-
- $project
- $addFields
info
- Using $project
- Using $addFields
db.books.aggregate([
{
$match: { year: { $gt: 2000 } }
},
{
$match: {
authors: { $exists: true },
}
},
{
$addFields: {
numAuthors: { $size: "$authors" },
}
},
{
$sort: { "numAuthors": -1 }
},
{
$limit: 1
}
]);
db.books.aggregate([
{
$match: { year: { $gt: 2000 } }
},
{
$match: {
authors: { $exists: true },
}
},
{
$addFields: {
numAuthors: { $size: "$authors" },
}
},
{
$sort: { "numAuthors": -1 }
},
{
$limit: 1
}
]);