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
Retrieving group by result with arrays in MongoDB?
To retrieve group by result with arrays in MongoDB, use aggregate() with $unwind and $group stages. The $addToSet operator adds values to an array unless the value is already present, preventing duplicates.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayField" },
{
$group: {
_id: "$fieldToGroupBy",
resultArray: { $addToSet: "$fieldToCollect" }
}
}
])
Sample Data
db.demo498.insertMany([
{ id: 1, Name: ["Chris"] },
{ id: 2, Name: ["David"] },
{ id: 3, Name: ["Chris"] },
{ id: 4, Name: ["Bob"] },
{ id: 5, Name: ["David"] }
])
{
"acknowledged": true,
"insertedIds": {
"0": ObjectId("..."),
"1": ObjectId("..."),
"2": ObjectId("..."),
"3": ObjectId("..."),
"4": ObjectId("...")
}
}
Display all documents from the collection ?
db.demo498.find()
{ "_id": ObjectId("5e86192b987b6e0e9d18f553"), "id": 1, "Name": ["Chris"] }
{ "_id": ObjectId("5e86192d987b6e0e9d18f554"), "id": 2, "Name": ["David"] }
{ "_id": ObjectId("5e861931987b6e0e9d18f555"), "id": 3, "Name": ["Chris"] }
{ "_id": ObjectId("5e861942987b6e0e9d18f556"), "id": 4, "Name": ["Bob"] }
{ "_id": ObjectId("5e861947987b6e0e9d18f557"), "id": 5, "Name": ["David"] }
Group by Names and Collect IDs
Retrieve group by result with arrays to collect all id values for each unique name ?
db.demo498.aggregate([
{
$unwind: "$Name"
},
{
$group: {
_id: "$Name",
Id: {
$addToSet: "$id"
}
}
}
])
{ "_id": "David", "Id": [5, 2] }
{ "_id": "Bob", "Id": [4] }
{ "_id": "Chris", "Id": [3, 1] }
How It Works
-
$unwind− Deconstructs theNamearray, creating separate documents for each array element -
$group− Groups documents by theNamefield value -
$addToSet− Collects uniqueidvalues into an array for each group
Conclusion
Use $unwind to flatten arrays, then $group with $addToSet to create grouped results with collected values. This approach effectively groups documents by array elements and aggregates related data.
Advertisements
