Calculate frequency of duplicate names from NAME field using MongoDB aggregate?


To calculate frequency, group with $group in aggregate(). Let us create a collection with documents −

> db.demo635.insertOne({Name:"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c10f06c954c74be91e6cc")
}
> db.demo635.insertOne({Name:"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c10f46c954c74be91e6cd")
}
> db.demo635.insertOne({Name:"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c10f66c954c74be91e6ce")
}
> db.demo635.insertOne({Name:"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c10f86c954c74be91e6cf")
}
> db.demo635.insertOne({Name:"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c10fb6c954c74be91e6d0")
}
> db.demo635.insertOne({Name:"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c10fc6c954c74be91e6d1")
}

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

> db.demo635.find();

This will produce the following output −

{ "_id" : ObjectId("5e9c10f06c954c74be91e6cc"), "Name" : "Chris" }
{ "_id" : ObjectId("5e9c10f46c954c74be91e6cd"), "Name" : "David" }
{ "_id" : ObjectId("5e9c10f66c954c74be91e6ce"), "Name" : "David" }
{ "_id" : ObjectId("5e9c10f86c954c74be91e6cf"), "Name" : "Chris" }
{ "_id" : ObjectId("5e9c10fb6c954c74be91e6d0"), "Name" : "Bob" }
{ "_id" : ObjectId("5e9c10fc6c954c74be91e6d1"), "Name" : "Chris" }

Following is the query to calculate frequency using MongoDB aggregate framework −

> db.demo635.aggregate([
...    { $unwind: "$Name" },
...    { $group: { "_id": "$Name", TotalFrequency: { $sum : 1 } } }
...    ]
... );

This will produce the following output −

{ "_id" : "David", "TotalFrequency" : 2 }
{ "_id" : "Bob", "TotalFrequency" : 1 }
{ "_id" : "Chris", "TotalFrequency" : 3 }

Updated on: 12-May-2020

116 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements