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
Group all documents with common fields in MongoDB?
To group all documents with common fields in MongoDB, use the $group aggregation stage with $addToSet operator. This accumulates unique values from documents that share the same field value.
Syntax
db.collection.aggregate([
{
$group: {
_id: "$fieldToGroupBy",
"groupedField": { $addToSet: "$fieldToAccumulate" }
}
}
]);
Sample Data
db.findDocumentWithCommonFieldsDemo.insertMany([
{ "UserId": 1, "UserName": "Carol" },
{ "UserId": 2, "UserName": "David" },
{ "UserId": 1, "UserName": "Sam" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cdf8ebebf3115999ed51200"),
ObjectId("5cdf8ebebf3115999ed51201"),
ObjectId("5cdf8ebebf3115999ed51202")
]
}
View Sample Data
db.findDocumentWithCommonFieldsDemo.find();
{ "_id": ObjectId("5cdf8ebebf3115999ed51200"), "UserId": 1, "UserName": "Carol" }
{ "_id": ObjectId("5cdf8ebebf3115999ed51201"), "UserId": 2, "UserName": "David" }
{ "_id": ObjectId("5cdf8ebebf3115999ed51202"), "UserId": 1, "UserName": "Sam" }
Group Documents by Common Fields
Group all documents by UserId and collect unique UserName values ?
db.findDocumentWithCommonFieldsDemo.aggregate([
{
$group: {
_id: "$UserId",
"UserDetails": { $addToSet: "$UserName" }
}
}
]);
{ "_id": 2, "UserDetails": [ "David" ] }
{ "_id": 1, "UserDetails": [ "Sam", "Carol" ] }
Key Points
-
$groupgroups documents by the specified field (_idfield in the group stage). -
$addToSetcreates an array of unique values from the grouped documents. - Documents with
UserId: 1are grouped together with their uniqueUserNamevalues.
Conclusion
Use $group with $addToSet to efficiently group documents by common field values and accumulate unique data from those groups. This approach eliminates duplicates while preserving all distinct values.
Advertisements
