Get distinct pair of objects with all subdocuments in MongoDB?


To get a distinct pair of objects, use $group. Let us create a collection with documents −

> db.demo522.insertOne({"Name":"John","Score":45});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e89b646b3fbf26334ef611b")
}
> db.demo522.insertOne({"Name":"Bob","Score":67});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e89b64eb3fbf26334ef611c")
}
> db.demo522.insertOne({"Name":"John","Score":55});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e89b655b3fbf26334ef611d")
}
> db.demo522.insertOne({"Name":"Bob","Score":33});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e89b65cb3fbf26334ef611e")
}

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

> db.demo522.find();

This will produce the following output −

{ "_id" : ObjectId("5e89b646b3fbf26334ef611b"), "Name" : "John", "Score" : 45 }
{ "_id" : ObjectId("5e89b64eb3fbf26334ef611c"), "Name" : "Bob", "Score" : 67 }
{ "_id" : ObjectId("5e89b655b3fbf26334ef611d"), "Name" : "John", "Score" : 55 }
{ "_id" : ObjectId("5e89b65cb3fbf26334ef611e"), "Name" : "Bob", "Score" : 33 }

Following is the query to get a distinct pair of objects with all the subdocuments in MongoDB −

> var query = [
...    {
...       "$group": {
...          "_id": "$Name",
...          "Score": { "$sum": "$Score" }
...       }
...    },
...    {
...       "$project": {
...          "Name": "$_id", "_id": 0, "Score": 1
...       }
...    }
... ];
>
> db.demo522.aggregate(query);

This will produce the following output −

{ "Score" : 100, "Name" : "Bob" }
{ "Score" : 100, "Name" : "John" }

Updated on: 13-May-2020

275 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements