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

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



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 }
Updated on: 2020-05-14T08:11:54+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements