How can I extract entire documents based on how they compare with their whole collection?


For this, use $$ROOT in MongoDB. Let us create a collection with documents −

> db.demo743.insertOne({id:1,"ShippingDate":"2020-01-21",value:50});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ead893a57bb72a10bcf0680")
}
> db.demo743.insertOne({id:2,"ShippingDate":"2020-05-10",value:30});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ead893c57bb72a10bcf0681")
}
> db.demo743.insertOne({id:3,"ShippingDate":"2020-05-10",value:60});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ead894657bb72a10bcf0682")
}
> db.demo743.insertOne({id:1,"ShippingDate":"2020-05-11",value:75});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ead895657bb72a10bcf0683")
}

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

> db.demo743.find();

This will produce the following output −

{ "_id" : ObjectId("5ead893a57bb72a10bcf0680"), "id" : 1, "ShippingDate" : "2020-01-21", "value" : 50 }
{ "_id" : ObjectId("5ead893c57bb72a10bcf0681"), "id" : 2, "ShippingDate" : "2020-05-10", "value" : 30 }
{ "_id" : ObjectId("5ead894657bb72a10bcf0682"), "id" : 3, "ShippingDate" : "2020-05-10", "value" : 60 }
{ "_id" : ObjectId("5ead895657bb72a10bcf0683"), "id" : 1, "ShippingDate" : "2020-05-11", "value" : 75 }

Following is the query to extract entire documents based on how they compare with their whole collection −

> 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}
...    }
... ])

This will produce the following output −

{ "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 } }

Updated on: 30-Jun-2020

60 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements