Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count records with one distinct field in mongoose?

While exploring mongoose for nodejs I ran into the problem of needing to know the amount of user in my collection:

My collection has records, each record has a user. I want to know the amount of unique (different) users.

How can I do this with mongoose?

EDIT:

The database is growing quite fast, is there anyway to get the number back from the DB instead of getting all the distinct records and counting them?

like image 879
askmike Avatar asked Sep 16 '12 23:09

askmike


People also ask

How to count distinct values in mongoose?

If you just want the count without getting the values, stick a count() call in the chain: Record. distinct('user_id'). count().

How can I count distinct values in MongoDB?

To count the unique values, use "distinct()" rather than "find()", and "length" rather than "count()". The first argument for "distinct" is the field for which to aggregate distinct values, the second is the conditional statement that specifies which rows to select.

How to use distinct in MongoDB?

distinct() considers each element of the array as a separate value. For instance, if a field has as its value [ 1, [1], 1 ] , then db. collection. distinct() considers 1 , [1] , and 1 as separate values.

How do you sum in mongoose?

One such operator is $sum. As the name suggests, the $sum operator is used to get the sum of numerical values. It is commonly used with $match and $group.


1 Answers

Aggregation will work for you. Something like that:

Transaction.aggregate(
    { $match: { seller: user, status: 'completed'  } }, 
    { $group: { _id: '$customer', count: {$sum: 1} } }
).exec() 
like image 159
aaronheckmann Avatar answered Oct 26 '22 23:10

aaronheckmann