What is $$ROOT in MongoDB aggregate and how it works?

Viewed 18117

I am watching a tutorial I can understand how this aggregate works, What is the use of pings, $$ROOT in it.

client = pymongo.MongoClient(MY_URL)
pings = client['mflix']['watching_pings']
cursor = pings.aggregate([
  {
    "$sample": { "size": 50000 }
  },
  {
    "$addFields": { 
      "dayOfWeek": { "$dayOfWeek": "$ts" },
      "hourOfDay": { "$hour": "$ts" }
    }
  },
  {
    "$group": { "_id": "$dayOfWeek", "pings": { "$push": "$$ROOT" } }
  },
  {
    "$sort": { "_id": 1 }
  }
]);
1 Answers

Let's assume that our collection looks like below:

{
    "_id" : ObjectId("b9"),
    "key" : 1,
    "value" : 20,
    "history" : ISODate("2020-05-16T00:00:00Z")
},
{
    "_id" : ObjectId("ba"),
    "key" : 1,
    "value" : 10,
    "history" : ISODate("2020-05-13T00:00:00Z")
},
{
    "_id" : ObjectId("bb"),
    "key" : 3,
    "value" : 50,
    "history" : ISODate("2020-05-12T00:00:00Z")
},
{
    "_id" : ObjectId("bc"),
    "key" : 2,
    "value" : 0,
    "history" : ISODate("2020-05-13T00:00:00Z")
},
{
    "_id" : ObjectId("bd"),
    "key" : 2,
    "value" : 10,
    "history" : ISODate("2020-05-16T00:00:00Z")
}

Now based on the history field you want to group and insert the whole documents in to an array field 'items'. Here $$ROOT variable will be helpful.

So, the aggregation query to achieve the above will be:

db.collection.aggregate([{
    $group: {
        _id: '$history',
        items: {$push: '$$ROOT'}
    }
}])

It will result in following output:

{
    "_id" : ISODate("2020-05-12T00:00:00Z"),
    "items" : [
        {
            "_id" : ObjectId("bb"),
            "key" : 3,
            "value" : 50,
            "history" : ISODate("2020-05-12T00:00:00Z")
        }
    ]
},
{
    "_id" : ISODate("2020-05-13T00:00:00Z"),
    "items" : [
        {
            "_id" : ObjectId("ba"),
            "key" : 1,
            "value" : 10,
            "history" : ISODate("2020-05-13T00:00:00Z")
        },
        {
            "_id" : ObjectId("bc"),
            "key" : 2,
            "value" : 0,
            "history" : ISODate("2020-05-13T00:00:00Z")
        }
    ]
},
{
    "_id" : ISODate("2020-05-16T00:00:00Z"),
    "items" : [
        {
            "_id" : ObjectId("b9"),
            "key" : 1,
            "value" : 20,
            "history" : ISODate("2020-05-16T00:00:00Z")
        },
        {
            "_id" : ObjectId("bd"),
            "key" : 2,
            "value" : 10,
            "history" : ISODate("2020-05-16T00:00:00Z")
        }
    ]
}

I hope it helps.

Related