如何计算猫鼬中一个不同字段的记录? [英] How to count records with one distinct field in mongoose?

查看:44
本文介绍了如何计算猫鼬中一个不同字段的记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在探索Nodejs的猫鼬时,我遇到了需要知道集合中用户数量的问题:

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.

我怎么用猫鼬呢?

数据库的增长非常快,是否有从数据库取回数字的方法,而不是获取所有不同的记录并对其进行计数?

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?

推荐答案

这里是一个替代答案,因为当我尝试使用Reddest的Mongoose 3.1.2方法时出现异常(这对Reddest的方法来说应该是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).

您可以在集合模型上调用distinct方法,指定该集合的用户标识字段的名称:

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

或者,如果您要链接查找中的distinct调用,请将回调包含在distinct调用中(这确实对我有用):

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

更新

如果只希望计数而不获取值,请在链中添加一个count()调用:

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

注意:这不适用于最新的Mongoose代码(3.5.2).

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

这篇关于如何计算猫鼬中一个不同字段的记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆