Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Find values group by another field in MongoDB?
To group by another field in MongoDB, use $group along with $project. This approach allows you to aggregate documents based on a specific field while collecting values from other fields.
Syntax
db.collection.aggregate([
{$match: {field: "value"}},
{$group: {"_id": "$groupByField", "collectedField": {$addToSet: "$fieldToCollect"}}},
{$project: {"_id": 0, "groupByField": "$_id", "collectedField": 1}}
]);
Sample Data
db.demo374.insertMany([
{
"Name": "Chris",
"HobbyDetails": ["Reading Book", "Playing Football"],
"CountryName": "US"
},
{
"Name": "Chris",
"HobbyDetails": ["Browsing Internet", "Playing Football"],
"CountryName": "US"
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e5a04402ae06a1609a00b04"),
ObjectId("5e5a04402ae06a1609a00b05")
]
}
Display Documents
db.demo374.find();
{ "_id": ObjectId("5e5a04402ae06a1609a00b04"), "Name": "Chris", "HobbyDetails": [ "Reading Book", "Playing Football" ], "CountryName": "US" }
{ "_id": ObjectId("5e5a04402ae06a1609a00b05"), "Name": "Chris", "HobbyDetails": [ "Browsing Internet", "Playing Football" ], "CountryName": "US" }
Example: Group Hobbies by Name
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"]}
}
}
}}
]);
{
"Name": "Chris",
"HobbyDetails": [
"Browsing Internet",
"Playing Football",
"Reading Book",
"Playing Football"
]
}
How It Works
-
$matchfilters documents by CountryName -
$groupgroups by Name and collects HobbyDetails arrays using$addToSet -
$projectreshapes output and flattens nested arrays using$reduce
Conclusion
Use $group with $addToSet to collect values by another field. Combine with $reduce and $concatArrays to flatten nested arrays when needed.
Advertisements
