簡體   English   中英

如何計算mongodb中兩個集合中字段的不同值的數量

[英]how to count number of distinct values of a field from two collections in mongodb

我必須使用mongoDB集合A和B.它們都有“用戶”字段。 我想知道A,B和(A + B)中不同用戶的數量。 偽代碼如下:

A.user.distinct().count()
B.user.distinct().count()
(A.user union B.user)..distinct().count()

有人能提出一些建議嗎?

您不能使用帶有distinct count()來獲取集合中不同用戶的數量,因為它不是數組方法而distinct返回數組。 您需要使用Array.length屬性

要獲取A或B中不同用戶的數量,請使用以下命令

db.A.distinct('user').length
db.B.distinct('user').length

要獲取A union B中不同用戶的數量,請使用Array.prototype.concat()Array.prototype.filter()

var users = db.A.distinct('user');
users = users.concat(db.B.distinct('user'));
var num = users.filter(function(u, pos) {return users.indexOf(u) == pos; });
num.length;

要獲取每個集合中不同用戶的數量,您可以在mongo shell中運行以下命令:

db.A.distinct("user").length;
db.B.distinct("user").length;

為了獲得AB A並集中的不同用戶的數量,我將首先為每個集合檢索不同的數組,然后對數組進行並集並找到長度。 如果您使用的是JavaScript,我建議您使用Underscore.jsunion()方法來執行此操作。 它的用法在這里解釋。 請注意,您可以通過在shell中運行以下命令將mongo (或任何JavaScript文件)加載到mongo shell:

load("path/to/underscore.js");

然后,您可以輕松運行以下內容:

var a = db.A.distinct("user");
var b = db.B.distinct("user");
_.union(a, b).length;

否則,你可以實現自己的JavaScript函數,如解釋在這里你的應用程序的語言,或一個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM