简体   繁体   English

如何计算mongodb中两个集合中字段的不同值的数量

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

I have to mongoDB collection A and B. Both of them have the field 'user'. 我必须使用mongoDB集合A和B.它们都有“用户”字段。 I would like to know the number of distinct users in A, B, and (A + B). 我想知道A,B和(A + B)中不同用户的数量。 Pseudo code would be like the following: 伪代码如下:

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

Can someone give some suggestions? 有人能提出一些建议吗?

You can't use count() with distinct to get the number of distinct users in your collection because It is not an array method and distinct returns an array. 您不能使用带有distinct count()来获取集合中不同用户的数量,因为它不是数组方法而distinct返回数组。 You need to use the Array.length property 您需要使用Array.length属性

To get the number of distinct users in A or B use the following 要获取A或B中不同用户的数量,请使用以下命令

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

To get the number of distinct users in A union B use Array.prototype.concat() and Array.prototype.filter() 要获取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;

To get the number of distinct users in each collection you can run the following in the mongo shell: 要获取每个集合中不同用户的数量,您可以在mongo shell中运行以下命令:

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

To get the number of distinct users in the union of A and B I would first retrieve the distinct arrays for each collection and then do a union of the arrays and find the length. 为了获得AB A并集中的不同用户的数量,我将首先为每个集合检索不同的数组,然后对数组进行并集并找到长度。 If you're using JavaScript, I would recommend using Underscore.js ' union() method to do it. 如果您使用的是JavaScript,我建议您使用Underscore.jsunion()方法来执行此操作。 Its usage is explained here . 它的用法在这里解释。 Note that you can load Underscore.js (or any JavaScript file) to the mongo shell by running the following command from within the shell: 请注意,您可以通过在shell中运行以下命令将mongo (或任何JavaScript文件)加载到mongo shell:

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

Then you can easily run the following: 然后,您可以轻松运行以下内容:

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

Otherwise you can implement your own JavaScript function, as explained here , or one in the language of your application. 否则,你可以实现自己的JavaScript函数,如解释在这里你的应用程序的语言,或一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM