我需要操作mongoDB中的A和B两个集合,它们都有一个名为'user'的字段。我想知道A、B以及(A + B)中不同用户的数量。 伪代码如下:
A.user.distinct().count()
B.user.distinct().count()
(A.user union B.user)..distinct().count()
有人可以提供一些建议吗?
我需要操作mongoDB中的A和B两个集合,它们都有一个名为'user'的字段。我想知道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
Array.prototype.concat()
和 Array.prototype.filter()
来获取 A 和 B 的不同用户数。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;
A
和B
的不同用户数量,我会首先检索每个集合的不同数组,然后对数组进行联合并计算长度。如果您正在使用JavaScript,则建议使用Underscore.js 的union()
方法来完成此操作。其用法在此处有解释。请注意,您可以通过在shell内运行以下命令来加载Underscore.js(或任何JavaScript文件)到mongo
shell中:load("path/to/underscore.js");
var a = db.A.distinct("user");
var b = db.B.distinct("user");
_.union(a, b).length;