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
How can I extract entire documents based on how they compare with their whole collection?
To extract entire documents based on how they compare with their whole collection in MongoDB, use the $$ROOT variable within an aggregation pipeline. This allows you to preserve complete documents while performing grouping and comparison operations.
Syntax
db.collection.aggregate([
{
$project: {
"field1": "$field1",
"field2": "$field2",
"document": "$$ROOT"
}
},
{ $sort: { "field": 1 } },
{
$group: {
"_id": { "groupField": "$field" },
"result": { "$first": "$document" }
}
}
]);
Sample Data
db.demo743.insertMany([
{ id: 1, "ShippingDate": "2020-01-21", value: 50 },
{ id: 2, "ShippingDate": "2020-05-10", value: 30 },
{ id: 3, "ShippingDate": "2020-05-10", value: 60 },
{ id: 1, "ShippingDate": "2020-05-11", value: 75 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("..."),
ObjectId("..."),
ObjectId("..."),
ObjectId("...")
]
}
Example: Get Latest Document per ID
Extract the most recent document for each id based on ShippingDate ?
db.demo743.aggregate([
{
"$project": {
"id": "$id",
"ShippingDate": "$ShippingDate",
"MyDoc": "$$ROOT"
}
},
{
"$sort": { "ShippingDate": -1 }
},
{
"$group": {
"_id": { "id": "$id" },
"Result": { "$first": "$MyDoc" }
}
},
{
"$project": {
"Result.ShippingDate": 1,
"Result.id": 1,
"Result.value": 1,
"_id": 0
}
}
]);
{ "Result": { "id": 3, "ShippingDate": "2020-05-10", "value": 60 } }
{ "Result": { "id": 2, "ShippingDate": "2020-05-10", "value": 30 } }
{ "Result": { "id": 1, "ShippingDate": "2020-05-11", "value": 75 } }
How It Works
-
$$ROOTcaptures the entire original document in the$projectstage -
$sortorders documents byShippingDate(descending for latest first) -
$groupgroups byidand uses$firstto get the top document per group -
$projectreshapes the output to show only required fields
Conclusion
Use $$ROOT in aggregation pipelines to preserve entire documents while performing collection-wide comparisons and grouping operations. This technique is essential for extracting complete records based on specific criteria across the whole collection.
Advertisements
