問題描述
在為 nodejs 探索 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?
數據庫增長很快,有沒有辦法從數據庫中取回數字而不是獲取所有不同的記錄并計算它們?
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 方法時遇到異常(這對我來說似乎是 Mongoose 中的一個錯誤,因為 Reddest 的方法應該沒事).
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).
這篇關于如何計算貓鼬中具有一個不同字段的記錄?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!