Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count occurrences of duplicate values

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.

like image 340
user3871 Avatar asked Jan 06 '16 23:01

user3871


People also ask

How do you count duplicates in a list?

If you want to count duplicates for a given element then use the count() function. Use a counter() function or basics logic combination to find all duplicated elements in a list and count them in Python.

How do I count duplicates in Excel using Vlookup?

Just create the formula =VLOOKUP(List-1, List-2,True,False) and add it to a third column. The List-1 data will be searched in List-2. If there are any duplicates, then these will be listed in the third column where the formula was placed.


1 Answers

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
        }
)
like image 118
styvane Avatar answered Sep 22 '22 17:09

styvane