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
Getting a list of values by using MongoDB $group?
To get a list of values using MongoDB, use the $group aggregation stage along with the $push operator. This approach groups documents by a specific field and creates an array of values from another field.
Syntax
db.collection.aggregate([
{
$group: {
_id: "$groupingField",
arrayField: { $push: "$fieldToCollect" }
}
}
]);
Sample Data
First, let's create a collection with sample documents ?
db.groupByDemo.insertMany([
{ "UserName": "John", "Subject": "MongoDB" },
{ "UserName": "Larry", "Subject": "MySQL" },
{ "UserName": "John", "Subject": "Java" },
{ "UserName": "John", "Subject": "C" },
{ "UserName": "Larry", "Subject": "SQL Server" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd69f0457806ebf1256f136"),
ObjectId("5cd69f0657806ebf1256f137"),
ObjectId("5cd69f0d57806ebf1256f138"),
ObjectId("5cd69f1357806ebf1256f139"),
ObjectId("5cd69f1c57806ebf1256f13a")
]
}
Let's view all documents in the collection ?
db.groupByDemo.find().pretty();
{
"_id": ObjectId("5cd69f0457806ebf1256f136"),
"UserName": "John",
"Subject": "MongoDB"
}
{
"_id": ObjectId("5cd69f0657806ebf1256f137"),
"UserName": "Larry",
"Subject": "MySQL"
}
{
"_id": ObjectId("5cd69f0d57806ebf1256f138"),
"UserName": "John",
"Subject": "Java"
}
{
"_id": ObjectId("5cd69f1357806ebf1256f139"),
"UserName": "John",
"Subject": "C"
}
{
"_id": ObjectId("5cd69f1c57806ebf1256f13a"),
"UserName": "Larry",
"Subject": "SQL Server"
}
Example: Group Subjects by UserName
Now let's group documents by UserName and collect all subjects for each user ?
db.groupByDemo.aggregate([
{
$group: {
"_id": "$UserName",
"Subject": { $push: "$Subject" }
}
}
]);
{ "_id": "Larry", "Subject": [ "MySQL", "SQL Server" ] }
{ "_id": "John", "Subject": [ "MongoDB", "Java", "C" ] }
Key Points
-
$groupaggregates documents by the field specified in_id -
$pushcreates an array by collecting values from the specified field - The result shows each unique UserName with an array of all their subjects
Conclusion
The combination of $group and $push efficiently creates lists of values grouped by a common field. This technique is particularly useful for collecting related data points under shared identifiers.
Advertisements
