如何在mongoDB中获取多个匹配过滤器计数 [英] How to get multi matching filters count in mongoDB
问题描述
我收集了大约50000个文档.集合模式如下:
I have around 50000 documents in collection. Collections Schema looks like this:
{ param1: Boolean, param2: Boolean, param3: Boolean, param4: Boolean } //etc
我应该如何查询数据库,以获取每个匹配的参数计数. 目前,我正在循环调用每个参数:
How should i make query to db, to get each matching param count. Currently, I'm calling each param in a loop:
db.getCollection('patients').count({ param1: true } )
db.getCollection('patients').count({ param2: true } )
db.getCollection('patients').count({ param3: true } ) ...
我觉得这是不正确的方法,请给我一些建议,如何在一个查询中获取此信息.
I feel, this isn't right way, please give me some advise, how to get this information in one query.
推荐答案
通过 聚合框架 .
Very possible in one go via the aggregation framework.
在MongoDb 3.6和更高版本中,您可以利用 $arrayToObject
运算符> $replaceRoot
管道即可获得所需的结果.
With MongoDb 3.6 and newer, you can leverage the use of $arrayToObject
operator within a $replaceRoot
pipeline to get the desired result.
Within the pipeline, take advantage of the $cond
operator in the $group
stage to evaluate the counts based on the param field boolean value, something like the following:
db.getCollection('patients').aggregate([
{ "$project": { "_id": 0 } },
{ "$project": { "data": { "$objectToArray": "$$ROOT" } } },
{ "$unwind": "$data" },
{ "$group": {
"_id": "$data.k",
"count": {
"$sum": {
"$cond": [ "$data.v", 1, 0 ]
}
}
} },
{ "$group": {
"_id": null,
"counts": {
"$push": { "k": "$_id", "v": "$count" }
}
} },
{ "$project": {
"data": { "$arrayToObject": "$counts" }
} },
{ "$replaceRoot": { "newRoot": "$data" } }
])
对于不支持上述 的MongoDB版本$arrayToObject
和
For MongoDB versions that do not have support for the above $arrayToObject
and $replaceRoot
operators, you would need to explicitly specify the fields in the group pipeline when calculating the sums:
db.getCollection('patients').aggregate([
{ "$group": {
"_id": null,
"param1_count": {
"$sum": {
"$cond": [ "$param1", 1, 0 ] /* similar to "$cond": [ { "$eq": [ "$param1", true ] }, 1, 0 ] */
}
},
"param2_count": {
"$sum": {
"$cond": [ "$param2", 1, 0 ]
}
},
"param3_count": {
"$sum": {
"$cond": [ "$param3", 1, 0 ]
}
},
"param4_count": {
"$sum": {
"$cond": [ "$param4", 1, 0 ]
}
}
} },
{ "$project": {
"_id": 0,
"param_counts": {
"param1": "$param1_count",
"param2": "$param2_count",
"param3": "$param3_count",
"param4": "$param4_count"
}
} }
])
这篇关于如何在mongoDB中获取多个匹配过滤器计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!