Apply the Group Accumulator Operator $first on the system variable $$ROOT to return reference to the root document?


The accumulators are operators that maintain their state as documents progress through the pipeline.

The $ROOT references the root document, i.e. the top-level document, currently being processed in the aggregation pipeline stage.

Let us create a collection with documents −

> db.demo582.insertOne({FirstName:"Chris",Age:21,createDate:new ISODate("2020-01-10")});{
   "acknowledged" : true, "insertedId" : ObjectId("5e91ce41fd2d90c177b5bcbd")
}
> db.demo582.insertOne({FirstName:"Chris",Age:21,createDate:new ISODate("2020-04-21")});{
   "acknowledged" : true, "insertedId" : ObjectId("5e91ce4ffd2d90c177b5bcbe")
}
> db.demo582.insertOne({FirstName:"Chris",Age:22,createDate:new ISODate("2020-02-11")});{
   "acknowledged" : true, "insertedId" : ObjectId("5e91ce59fd2d90c177b5bcbf")
}
> db.demo582.insertOne({FirstName:"Chris",Age:22,createDate:new ISODate("2020-01-12")});{
   "acknowledged" : true, "insertedId" : ObjectId("5e91ce6efd2d90c177b5bcc0")
}

Display all documents from a collection with the help of find() method −

> db.demo582.find();

This will produce the following output −

{ "_id" : ObjectId("5e91ce41fd2d90c177b5bcbd"), "FirstName" : "Chris", "Age" : 21, "createDate" : ISODate("2020-01-10T00:00:00Z") }
{ "_id" : ObjectId("5e91ce4ffd2d90c177b5bcbe"), "FirstName" : "Chris", "Age" : 21, "createDate" : ISODate("2020-04-21T00:00:00Z") }
{ "_id" : ObjectId("5e91ce59fd2d90c177b5bcbf"), "FirstName" : "Chris", "Age" : 22, "createDate" : ISODate("2020-02-11T00:00:00Z") }
{ "_id" : ObjectId("5e91ce6efd2d90c177b5bcc0"), "FirstName" : "Chris", "Age" : 22, "createDate" : ISODate("2020-01-12T00:00:00Z") }

Following is the query to apply the Group Accumulator operator −

> db.demo582.aggregate([
...    {
...       "$group": {
...          "_id": "$FirstName",
...          "MaximumDate": {
...             "$max": "$createDate"
...          },
...          "count": {
...             "$sum": 1
...          },
...          "details": {
...             "$first": "$$ROOT"
...          }
...       }
...    },
...    {
...       "$project": {
...          "MaximumDate": 1,
...          "count": 1,
...          "details": {
...             "_id": "$_id",
...             "FirstName": "$details.FirstName",
...             "Age" : "$details.Age",
...          }
...       }
...    }
... ])

This will produce the following output −

{ "_id" : "Chris", "MaximumDate" : ISODate("2020-04-21T00:00:00Z"), "count" : 4, "details" :
   { "_id" : "Chris", "FirstName" : "Chris", "Age" : 21 }
}

Updated on: 15-May-2020

103 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements