MongoDB aggregate to get the count of field values of corresponding duplicate names?

MongoDBDatabaseBig Data Analytics

Let us see an example and create a collection with documents −

> db.demo558.insertOne(
... {
...    _id : 100,
...    CountryCode:101,
...    details: [
...       {
...          Name:"Chris",
...          Subject:"MySQL"
...       },
...       {
...          Name:"Chris",
...          Subject:"MongoDB"
...       },
...       {
...          Name:"Chris",
...          Subject:"Java"
...       },
...       {
...          Name:"Bob",
...          Subject:"Python"
...       },
...       {
...          Name:"Bob",
...          Subject:"Java"
...       }
...    ]
... }
... )
{ "acknowledged" : true, "insertedId" : 100 }

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

> db.demo558.find();

This will produce the following output −

{ "_id" : 100, "CountryCode" : 101, "details" : [
   { "Name" : "Chris", "Subject" : "MySQL" },
   { "Name" : "Chris", "Subject" : "MongoDB" },
   { "Name" : "Chris", "Subject" : "Java" },
   { "Name" : "Bob", "Subject" : "Python" },
   { "Name" : "Bob", "Subject" : "Java" }
] }

Following is the query to get the count −

> db.demo558.aggregate([
...    {$unwind: "$details" },
...    {$group: { _id: "$details.Name", NameCount:{$sum : 1}, Subject : {$push: "$details.Subject"}}},
...    {$project: { NameCount: 1, SubjectCount : {$size: "$Subject"}}}
... ]).pretty()

This will produce the following output −

{ "_id" : "Bob", "NameCount" : 2, "SubjectCount" : 2 }
{ "_id" : "Chris", "NameCount" : 3, "SubjectCount" : 3 }
raja
Published on 14-May-2020 08:10:53
Advertisements