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?
If you just want the count without getting the values, stick a count() call in the chain: Record. distinct('user_id'). count().
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.
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.
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.
Aggregation will work for you. Something like that:
Transaction.aggregate(
{ $match: { seller: user, status: 'completed' } },
{ $group: { _id: '$customer', count: {$sum: 1} } }
).exec()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With