To get the first and last document in MongoDB, use aggregate() along with $first and $last respectively. Let us create a collection with documents −
> db.demo73.insertOne({"Name":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e29c41b71bf0181ecc4226c")
}
.
> db.demo73.insertOne({"Name":"Bob"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e29c41e71bf0181ecc4226d")
}
> db.demo73.insertOne({"Name":"David"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e29c42271bf0181ecc4226e")
}Display all documents from a collection with the help of find() method −
> db.demo73.find();
This will produce the following output −
{ "_id" : ObjectId("5e29c41b71bf0181ecc4226c"), "Name" : "Chris" }
{ "_id" : ObjectId("5e29c41e71bf0181ecc4226d"), "Name" : "Bob" }
{ "_id" : ObjectId("5e29c42271bf0181ecc4226e"), "Name" : "David" }Following is the way to get the first and last document−
> db.demo73.aggregate({
... $group: {
... _id: null,
... first: { $first: "$$ROOT" },
... last: { $last: "$$ROOT" }
... }
... }
... );This will produce the following output −
{
"_id" : null, "first" : { "_id" : ObjectId("5e29c41b71bf0181ecc4226c"), "Name" : "Chris" }, "last" : {
"_id" : ObjectId("5e29c42271bf0181ecc4226e"), "Name" : "David"
}
}