How to count records with one distinct field in mongoose?

主宰稳场 提交于 2020-01-02 03:36:05

问题


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?


回答1:


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).




回答2:


Aggregation will work for you. Something like that:

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



回答3:


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



回答4:


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




回答5:


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


来源:https://stackoverflow.com/questions/12451575/how-to-count-records-with-one-distinct-field-in-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!