How to count records with one distinct field in mongoose? How to count records with one distinct field in mongoose? mongoose mongoose

How to count records with one distinct field in mongoose?


Here's an alternative answer as I get an exception when I try Reddest's approach with Mongoose 3.1.2 (which seems like a bug in Mongoose to me as Reddest's approach should be fine).

You can call the distinct method on your collection's model, specifying the name of the user-identifying field of that collection:

Record.distinct('user_id').exec(function (err, user_ids) {    console.log('The number of unique users is: %d', user_ids.length);});

Or if you want to chain the distinct call from a find, include the callback in the distinct call (this did work for me):

Record.find().distinct('user_id', function (err, user_ids) { ... });

UPDATE

If you just want the count without getting the values, stick a count() call in the chain:

Record.distinct('user_id').count().exec(function (err, count) {    console.log('The number of unique users is: %d', count);});

NOTE: this doesn't work in the latest Mongoose code (3.5.2).


Aggregation will work for you. Something like that:

Transaction.aggregate(    { $match: { seller: user, status: 'completed'  } },     { $group: { _id: '$customer', count: {$sum: 1} } }).exec() 


If you just want get the number of queried collections, you can use this:

Record.find()      .distinct('user_id')      .count(function (err, count) {          //The number of unique users is 'count'      });