To get the number of distinct users in each collection you can run the following in the 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. If you're using JavaScript, I would recommend using Underscore.js' union()
method to do it. 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:
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.