MongoDB aggregation of elements with similar ids in different documents?

MongoDBDatabaseBig Data Analytics

For such grouping of documents, use $group in MongoDB aggregate(). Let us create a collection with documents −

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

Display all documents from a collection with the help of find() method −

> db.demo602.find();

This will produce the following output −

{ "_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" }

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}
... );

This will produce the following output −

{ "_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 }
] }
raja
Published on 15-May-2020 11:13:28
Advertisements