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
MongoDB aggregate to convert multiple documents into single document with an array?
MongoDB aggregation pipeline allows you to group multiple documents into single documents containing arrays. Use the $group stage with $push operator to combine documents sharing a common field into a single document with an array field.
Syntax
db.collection.aggregate([
{
$group: {
_id: "$groupingField",
arrayField: {
$push: {
field1: "$field1",
field2: "$field2"
}
}
}
}
]);
Sample Data
db.demo248.insertMany([
{"id": 101, "Name": "Chris", "Age": 21, "CountryName": "US"},
{"id": 101, "Name": "Bob", "Age": 22, "CountryName": "UK"},
{"id": 102, "Name": "Mike", "Age": 20, "CountryName": "AUS"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e46b6651627c0c63e7dba6d"),
ObjectId("5e46b6741627c0c63e7dba6e"),
ObjectId("5e46b6811627c0c63e7dba6f")
]
}
Original Documents
db.demo248.find();
{"_id": ObjectId("5e46b6651627c0c63e7dba6d"), "id": 101, "Name": "Chris", "Age": 21, "CountryName": "US"}
{"_id": ObjectId("5e46b6741627c0c63e7dba6e"), "id": 101, "Name": "Bob", "Age": 22, "CountryName": "UK"}
{"_id": ObjectId("5e46b6811627c0c63e7dba6f"), "id": 102, "Name": "Mike", "Age": 20, "CountryName": "AUS"}
Example: Group by ID Field
Convert multiple documents into single documents with array by grouping on the id field ?
db.demo248.aggregate([
{
$group: {
_id: "$id",
details: {
$push: {
id: "$id",
Name: "$Name",
Age: "$Age",
CountryName: "$CountryName"
}
}
}
}
]);
{"_id": 102, "details": [{"id": 102, "Name": "Mike", "Age": 20, "CountryName": "AUS"}]}
{"_id": 101, "details": [{"id": 101, "Name": "Chris", "Age": 21, "CountryName": "US"}, {"id": 101, "Name": "Bob", "Age": 22, "CountryName": "UK"}]}
How It Works
-
$groupstage groups documents by the_idfield value -
$pushoperator adds each matching document to thedetailsarray - Documents with
id: 101are combined into one document with two array elements - Document with
id: 102creates a single-element array
Conclusion
The $group stage with $push operator effectively converts multiple related documents into single documents containing arrays. This is useful for organizing data by common identifiers or creating summary documents.
Advertisements
