MongoDB aggregation of elements with similar ids in different documents?

To aggregate elements with similar ids in different documents, use $group in MongoDB aggregation pipeline. This technique groups documents by id and collects all related data into arrays.

Syntax

db.collection.aggregate([
    { $group: {
        '_id': { id: "$id", "fieldName": "$fieldName" },
        "count": { "$sum": 1 }
    }},
    { $group: {
        '_id': "$_id.id",
        "aggregatedData": { "$push": { field: "$_id.fieldName", frequency: "$count" }}
    }}
]);

Sample Data

db.demo602.insertMany([
    { id: 1, Name: "Chris" },
    { id: 2, Name: "David" },
    { id: 1, Name: "Bob" },
    { id: 3, Name: "Mike" },
    { id: 2, Name: "John" },
    { id: 1, Name: "Sam" }
]);

Display all documents from the collection ?

db.demo602.find();
{ "_id" : ObjectId("5e960080ed011c280a0905c9"), "id" : 1, "Name" : "Chris" }
{ "_id" : ObjectId("5e960086ed011c280a0905ca"), "id" : 2, "Name" : "David" }
{ "_id" : ObjectId("5e96008ced011c280a0905cb"), "id" : 1, "Name" : "Bob" }
{ "_id" : ObjectId("5e960092ed011c280a0905cc"), "id" : 3, "Name" : "Mike" }
{ "_id" : ObjectId("5e960099ed011c280a0905cd"), "id" : 2, "Name" : "John" }
{ "_id" : ObjectId("5e9600a1ed011c280a0905ce"), "id" : 1, "Name" : "Sam" }

Example

Following is the query to aggregate elements with similar ids in different documents ?

db.demo602.aggregate([
    { $group: {
        '_id': { id: "$id", "Name": "$Name" },
        "count": { "$sum": 1 }
    }},
    { $group: {
        '_id': "$_id.id",
        "ListOfName": { "$push": { Name: "$_id.Name", Frequency: "$count" }}
    }}
], 
{ 'allowDiskUse': true });
{ "_id" : 2, "ListOfName" : [
    { "Name" : "John", "Frequency" : 1 },
    { "Name" : "David", "Frequency" : 1 }
] }
{ "_id" : 3, "ListOfName" : [
    { "Name" : "Mike", "Frequency" : 1 }
] }
{ "_id" : 1, "ListOfName" : [
    { "Name" : "Sam", "Frequency" : 1 },
    { "Name" : "Bob", "Frequency" : 1 },
    { "Name" : "Chris", "Frequency" : 1 }
] }

How It Works

  • First $group stage groups by both id and Name, counting occurrences
  • Second $group stage groups by id only, using $push to collect names into arrays
  • allowDiskUse: true enables disk usage for large datasets

Conclusion

Use nested $group stages in aggregation pipeline to group documents by similar IDs and collect related fields into arrays. This approach efficiently organizes data from multiple documents sharing common identifiers.

Updated on: 2026-03-15T03:48:12+05:30

723 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements