Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
计算MongoDB中的一组值_Mongodb_Count_Set - Fatal编程技术网

计算MongoDB中的一组值

计算MongoDB中的一组值,mongodb,count,set,Mongodb,Count,Set,我有一个MongoDB数据库,其中的文档包含一个用户字段。这些文档如下所示: {"_id" : ObjectId("4f98a564590f22a8b13e7df0"), "user" : ['pete', 'joe', 'sally'] ... } {"_id" : ObjectId("4f981426590f22a8b13e6b62"), "user" : ['tim', 'joe', 'sam'] ... } 如何构造查询来统计数据库中的所有用户集。对于上述两个单据,查询将返回计数5。

我有一个MongoDB数据库,其中的文档包含一个用户字段。这些文档如下所示:

{"_id" : ObjectId("4f98a564590f22a8b13e7df0"), "user" : ['pete', 'joe', 'sally'] ... }

{"_id" : ObjectId("4f981426590f22a8b13e6b62"), "user" : ['tim', 'joe', 'sam'] ... }
如何构造查询来统计数据库中的所有用户集。对于上述两个单据,查询将返回计数5。

您可以使用该功能;这是MongoDB提供的用于聚合数据的函数之一:

> db.test.insert({ "user": ["pete", "joe", "sally"]})
> db.test.insert({ "user": ["tim", "joe", "sam"]})
> db.test.find()
{ "_id" : ObjectId("4fb933d5e5d47740efd09ae4"), "user" : [ "pete", "joe", "sally" ] }
{ "_id" : ObjectId("4fb933e9e5d47740efd09ae5"), "user" : [ "tim", "joe", "sam" ] }
> db.test.distinct("user")
[ "joe", "pete", "sally", "sam", "tim" ]
> db.test.distinct("user").length
5

非常感谢。人们非常赞赏这个例子。