'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?



Solution 1:[1]

Aggregation will work for you. Something like that:

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

Solution 2:[2]

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'
      });

Solution 3:[3]

You can do a distinct query.

var Record = db.model('Record', yourSchema);
Record.find().distinct('user').exec(callback);

Mongoose Queries: http://mongoosejs.com/docs/queries.html

MongoDB distinct query: http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct

Solution 4:[4]

I just needed the number of distinct musicians, but some of the code above did not work for me. If I used count and distinct together I just got the total number.

This was my solution:

/**
 * Get number of distinct musicians
 */

myList.find()
    .distinct('musicianName')
    .exec(function (err, count) {
        console.log(count.length);
    });

Solution 5:[5]

I was searching for an answer & got this question, now I got the answer so replying to this question.

You can segregate all the users with similar property with below code. I have used email as an example you can change it. You will also get count of all the users with same value of the property you pick.

var agg = [{$group: {_id: "$email",total: {$sum: 1}}}];
User.aggregate(agg, function(err, logs){
  if (err) { return console.log(err); }
  return console.log(logs);
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Arend
Solution 2 ScorpioCPH
Solution 3 BadCanyon
Solution 4 Leopold Kristjansson
Solution 5 yash kothari