Yesterday, we saw how $sort worked. Now, let’s combine it with another aggregation stage, $limit, which returns a specified number of documents.
We have this sightings documents.
// db.sightings.find({})
[
{
_id: ObjectId("62cf2f0acfe5bbb25ee815fb"),
species_common: "Eastern Bluebird",
species_scientific: "Sialia sialis",
date: ISODate("2022-01-17T18:24:00.000Z"),
location: { type: "Point", coordinates: [41, -74] },
},
{
_id: ObjectId("62cf8ebfbb9cdbee29caab04"),
species_common: "Eastern Bluebird",
species_scientific: "Sialia sialis",
date: ISODate("2022-01-18T21:09:00.000Z"),
location: { type: "Point", coordinates: [40, -74] },
},
{
_id: ObjectId("62e2d811b1d5bc85b6e04013"),
species_common: "Northern Cardinal",
species_scientific: "Cardinalis Cardinalis",
date: ISODate("2022-01-18T05:30:40.000Z"),
location: { type: "Point", coordinates: [41, -74] },
},
{
_id: ObjectId("62cf8eb2bb9cdbee29caab03"),
species_common: "Eastern Bluebird",
species_scientific: "Sialia sialis",
date: ISODate("2022-01-18T23:55:40.000Z"),
location: { type: "Point", coordinates: [40, -74] },
},
{
_id: ObjectId("62cf8e9fbb9cdbee29caab02"),
species_common: "Eastern Bluebird",
species_scientific: "Sialia sialis",
date: ISODate("2022-01-18T18:22:20.000Z"),
location: { type: "Point", coordinates: [40, -74] },
},
{
_id: ObjectId("62cf32bdcfe5bbb25ee815fc"),
species_common: "Eastern Bluebird",
species_scientific: "Sialia sialis",
date: ISODate("2022-01-18T18:24:00.000Z"),
location: { type: "Point", coordinates: [40, -73] },
},
];
Suppose we want to see the top 4 sightings with largest latitude value. We use $sort first then its resulting documents are now going to be limited by the number set by $limit.
// db.sightings.aggregate([{$sort: {"location.coordinates.1": -1}}, {$limit: 4}])
[
{
_id: ObjectId("62cf32bdcfe5bbb25ee815fc"),
species_common: "Eastern Bluebird",
species_scientific: "Sialia sialis",
date: ISODate("2022-01-18T18:24:00.000Z"),
location: { type: "Point", coordinates: [40, -73] },
},
{
_id: ObjectId("62cf8eb2bb9cdbee29caab03"),
species_common: "Eastern Bluebird",
species_scientific: "Sialia sialis",
date: ISODate("2022-01-18T23:55:40.000Z"),
location: { type: "Point", coordinates: [40, -74] },
},
{
_id: ObjectId("62cf8ebfbb9cdbee29caab04"),
species_common: "Eastern Bluebird",
species_scientific: "Sialia sialis",
date: ISODate("2022-01-18T21:09:00.000Z"),
location: { type: "Point", coordinates: [40, -74] },
},
{
_id: ObjectId("62cf2f0acfe5bbb25ee815fb"),
species_common: "Eastern Bluebird",
species_scientific: "Sialia sialis",
date: ISODate("2022-01-17T18:24:00.000Z"),
location: { type: "Point", coordinates: [41, -74] },
},
];