MongoDB query to count the frequency of every element of the array



To count, you can also use aggregate() along with $sum. Let us create a collection with documents −

> db.demo184.insertOne({"Names":["Chris","David","Bob"]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e3999fb9e4f06af55199805") } > db.demo184.insertOne({"Names":["Chris","Mike"]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e399a0d9e4f06af55199806") } > db.demo184.insertOne({"Names":["Chris","Bob","Carol"]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e399a209e4f06af55199807") }

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

> db.demo184.find();

This will produce the following output −

{ "_id" : ObjectId("5e3999fb9e4f06af55199805"), "Names" : [ "Chris", "David", "Bob" ] } { "_id" : ObjectId("5e399a0d9e4f06af55199806"), "Names" : [ "Chris", "Mike" ] } { "_id" : ObjectId("5e399a209e4f06af55199807"), "Names" : [ "Chris", "Bob", "Carol" ] }

Following is the query to count the frequency of every element −

> db.demo184.aggregate([ ...   { "$unwind" : "$Names" }, ...   { "$group": { "_id": "$Names", "count": { "$sum": 1} } }, ...   { "$group": { ...      "_id": null, ...         "counts": { ...            "$push": { ...               "k": "$_id", ...               "v": "$count" ...            } ...         } ...      } }, ...      { "$replaceRoot": { ...         "newRoot": { "$arrayToObject": "$counts" } ...   } } ...])

This will produce the following output −

{ "Carol" : 1, "David" : 1, "Chris" : 3, "Bob" : 2, "Mike" : 1 }
Updated on: 2020-03-27T08:05:48+05:30

847 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements