๐ $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
- JavaScript
- C#
- Using $project
- Using $addFields
await books.aggregate([
{
$match: { year: { $gt: 2000 } }
},
{
$match: {
authors: { $exists: true }
}
},
{
$project: {
title: 1,
year: 1,
authors: 1,
numAuthors: { $size: "$authors" }
}
},
{
$sort: { numAuthors: -1 }
},
{
$limit: 1
}
]).toArray();
await books.aggregate([
{
$match: { year: { $gt: 2000 } }
},
{
$match: {
authors: { $exists: true },
}
},
{
$addFields: {
numAuthors: { $size: "$authors" },
}
},
{
$sort: { "numAuthors": -1 }
},
{
$limit: 1
}
]).toArray();
- Using $project
- Using $addFields
var pipeline = booksCollection.Aggregate()
.Match(b => b.Year > 2000)
.Match(Builders<Book>.Filter.Exists(b => b.Authors))
.Project(new BsonDocument
{
{ "title", 1 },
{ "year", 1 },
{ "authors", 1 },
{ "numAuthors", new BsonDocument("$size", "$authors") }
})
.Sort(new BsonDocument("numAuthors", -1))
.Limit(1);
var mostAuthors = await pipeline.ToListAsync();
var pipeline = booksCollection.Aggregate()
.Match(b => b.Year > 2000)
.Match(Builders<Book>.Filter.Exists(b => b.Authors))
.AppendStage<BsonDocument>(
new BsonDocument("$addFields",
new BsonDocument("numAuthors", new BsonDocument("$size", "$authors"))
)
)
.Sort(new BsonDocument("numAuthors", -1))
.Limit(1);
var mostAuthors = pipeline.ToList();