Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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"
]
}Advertisements