Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
In MongoDB, what is the most efficient way to get the first and last document?
To get the first and last document in MongoDB, use aggregate() with $first and $last operators within a $group stage. This efficiently retrieves both documents in a single operation.
Syntax
db.collection.aggregate([
{
$group: {
_id: null,
first: { $first: "$$ROOT" },
last: { $last: "$$ROOT" }
}
}
]);
Sample Data
db.demo73.insertMany([
{"Name": "Chris"},
{"Name": "Bob"},
{"Name": "David"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e29c41b71bf0181ecc4226c"),
ObjectId("5e29c41e71bf0181ecc4226d"),
ObjectId("5e29c42271bf0181ecc4226e")
]
}
Display All Documents
db.demo73.find();
{ "_id": ObjectId("5e29c41b71bf0181ecc4226c"), "Name": "Chris" }
{ "_id": ObjectId("5e29c41e71bf0181ecc4226d"), "Name": "Bob" }
{ "_id": ObjectId("5e29c42271bf0181ecc4226e"), "Name": "David" }
Get First and Last Document
db.demo73.aggregate([
{
$group: {
_id: null,
first: { $first: "$$ROOT" },
last: { $last: "$$ROOT" }
}
}
]);
{
"_id": null,
"first": { "_id": ObjectId("5e29c41b71bf0181ecc4226c"), "Name": "Chris" },
"last": { "_id": ObjectId("5e29c42271bf0181ecc4226e"), "Name": "David" }
}
How It Works
-
$groupwith_id: nullprocesses all documents as one group -
$firstreturns the first document in processing order -
$lastreturns the last document in processing order -
$$ROOTrefers to the entire document
Conclusion
Using aggregate() with $first and $last operators is the most efficient way to retrieve both the first and last documents in a single query. The $$ROOT variable captures complete document details.
Advertisements
