MongoDB聚合管道查找布尔值



我希望找出集合中MatchCondition所匹配的所有文档错误是。我正在尝试使用匹配操作符在聚合管道中执行此操作,但这不起作用。

{
"_id": {
"$oid": "98rr6c03a82b7785f372c018"
},
"document": "DocumentName",
"ecuCheckResultList": [
{
"animal": "CAT",
"attribute1": "value",
"attribute2": "value",
"MatchCondition": true
},
{
"animal": "DOG",
"attribute1": "value",
"MatchCondition": false
}
]
}

我知道有一些选项可以使用find来做到这一点,但是需要对这些数据进行单独的操作,所以使用聚合管道。

最后,我需要找出集合中MatchCondition = false的每种动物的总数

在我的集合中有超过190万的文档,我想查询这些数据。

Query1

  • unwind replace root使每个成员都成为根文档
  • 匹配条件为false
  • 按动物和计数分组

Playmongo
(对于每个阶段的in/out,您可以将鼠标放置在舞台的末端)

aggregate(
[{"$unwind": "$ecuCheckResultList"},
{"$replaceRoot": {"newRoot": "$ecuCheckResultList"}},
{"$match": {"$expr": {"$eq": ["$MatchCondition", false]}}},
{"$group": {"_id": "$animal", "count": {"$sum": 1}}}])

Query2

  • 与上面相同,但首先过滤以只保留条件false并在
  • 后展开

*可能比前面的

快Playmongo

aggregate(
[{"$set": 
{"ecuCheckResultList": 
{"$filter": 
{"input": "$ecuCheckResultList",
"cond": {"$eq": ["$$this.MatchCondition", false]}}}}},
{"$unwind": "$ecuCheckResultList"},
{"$group": {"_id": "$ecuCheckResultList.animal", "count": {"$sum": 1}}}])

您可以$map构造一个辅助布尔数组来检查MatchCondition是否为假。对于您的情况,简单的$not将起作用,因为它可以将假转换为真。然后,使用$anyElementTrue执行过滤。

db.collection.aggregate([
{
"$match": {
$expr: {
"$anyElementTrue": {
"$map": {
"input": "$ecuCheckResultList.MatchCondition",
"as": "mc",
"in": {
$not: "$$mc"
}
}
}
}
}
}
])

这是Mongo游乐场供您参考。

最新更新