Count occurrences of duplicate values

Growler picture Growler · Jan 7, 2016 · Viewed 7.4k times · Source

How do I structure my MongooseJS/MongoDB query to get total duplicates/occurrences of a particular field value? Aka: The total documents with custID of some value for all custIDs

I can do this manually in command line:

db.tapwiser.find({"custID" : "12345"}, {}, {}).count();

Outputs: 1

db.tapwiser.find({"custID" : "6789"}, {}, {}).count();

Outputs: 4


I found this resource:

How to sum distinct values of a field in a MongoDB collection (utilizing mongoose)

But it requires that I specify the unique fields I want to sum.

In this case, I want to loop through all documents, sum the occurrences of each.

Answer

styvane picture styvane · Jan 7, 2016

All you need to do is $group your documents by custID and use the $sum accumulator operator to return "count" for each group.

db.tapwiser.aggregate(
    [ 
        { "$group":  { "_id": "$custID", "count": { "$sum": 1 } } }
    ],  function(err, results) {
            // Do something with the results
        }
)