我有一个MongoDB数据库,其中包含包含用户字段的文档。文档如下所示:
{"_id" : ObjectId("4f98a564590f22a8b13e7df0"), "user" : ['pete', 'joe', 'sally'] ... }
{"_id" : ObjectId("4f981426590f22a8b13e6b62"), "user" : ['tim', 'joe', 'sam'] ... }如何构造一个查询来计算我的数据库中所有用户的集合。对于上述两个文档,查询将返回计数5。
发布于 2012-05-21 02:17:23
您可以使用distinct()函数;它是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
5https://stackoverflow.com/questions/10675342
复制相似问题