Find values group by another field in MongoDB?


To group by another field, use $group along with $project. Let us first create a collection with documents −

> db.demo374.insertOne(
...    {
...
...       "Name" : "Chris",
...       "HobbyDetails" : [
...          "Reading Book",
...          "Playing Football"
...       ],
...       "CountryName" : "US"
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5a04402ae06a1609a00b04")
}
> db.demo374.insertOne(
...    {
...
...       "Name" : "Chris",
...       "HobbyDetails" : [
...          "Browsing Internet",
...          "Playing Football"
...       ],
...       "CountryName" : "US"
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5a04402ae06a1609a00b05")
}

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

> db.demo374.find();

This will produce the following output −

{ "_id" : ObjectId("5e5a04402ae06a1609a00b04"), "Name" : "Chris", "HobbyDetails" : [ "Reading Book", "Playing Football" ], "CountryName" : "US" }
{ "_id" : ObjectId("5e5a04402ae06a1609a00b05"), "Name" : "Chris", "HobbyDetails" : [ "Browsing Internet", "Playing Football" ], "CountryName" : "US" }

Following is the query to find values group by another field in MongoDB −

> db.demo374.aggregate([
...    {$match : { "CountryName" : "US"}},
...    {$group : {"_id" : "$Name", "HobbyDetails" : {$addToSet : "$HobbyDetails"}}},
...    {$project : {"_id" : 0, "Name" : "$_id", "HobbyDetails" : {$reduce : {input : "$HobbyDetails", initialValue : [], in: { $concatArrays : ["$$value", "$$this"] }}}}}
... ]).pretty()

This will produce the following output −

{
   "Name" : "Chris",
   "HobbyDetails" : [
      "Browsing Internet",
      "Playing Football",
      "Reading Book",
      "Playing Football"
   ]
}

Updated on: 02-Apr-2020

353 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements