我是 mongoDb 的新手,需要根据以下条件获取所有记录,需要将所有记录合并到单个过滤器中
状况
注意:该条件分别适用于以下所有清单(1、2、3 等)
样本数据
{
"ID": “1”,
"Name": “Demo1”,
"CheckList": {
“CheckList1”: {
"Status": "OPEN",
“Comments”: ""
},
"CheckList2”: {
"Status": "DONE",
"Comments": “Completed”
},
"CheckList3”: {
"Status": "NA",
"Comments": ""
},
"CheckList4”: {
"Status": "DONE",
"Comments": “Completed”
},
"CheckList5”: {
"Status": "NA",
"Comments": “not applicable”
},
}
},
需要原始类型 bson.D 的过滤器,我在下面尝试过,但没有返回记录,我知道这个过滤器有问题
filter := bson.D{
{“CheckList.CheckList1.Comments”, ""},
{“CheckList.CheckList2.Comments”, ""},
{“CheckList.CheckList3.Comments”, ""},
{“CheckList.CheckList4.Comments”, ""},
{“CheckList.CheckList5.Comments”, ""},
{"$or", bson.A{
bson.D{{"CheckList.CheckList1.Status", "NA"}},
bson.D{{"CheckList.CheckList1.Status", "OPEN"}},
bson.D{{"CheckList.CheckList2.Status", "NA"}},
bson.D{{"CheckList.CheckList2.Status", "OPEN"}},
bson.D{{"CheckList.CheckList3.Status", "NA"}},
bson.D{{"CheckList.CheckList3.Status”, "OPEN"}},
bson.D{{"CheckList.CheckList4.Status", "NA"}},
bson.D{{"CheckList.CheckList4.Status", "OPEN"}},
bson.D{{"CheckList.CheckList5.Status", "NA"}},
bson.D{{"CheckList.CheckList5.Status", "OPEN"}},
}}}
Cursor, err := db.example.find(filter)
请帮忙!
第二个和第三个条件可以单独组合成第三个条件,因为它们是 OR 条件。执行
$objectToArray
将对象转换为 k-v 元组数组,其中 v 作为 CheckList
对象的内容。然后,使用 $map
应用条件检查并映射到布尔数组。最后,在结果数组上使用 $allElementsTrue
作为最终的 $match
。
db.collection.aggregate([
{
"$set": {
"CheckList": {
"$objectToArray": "$CheckList"
}
}
},
{
"$match": {
"$expr": {
"$allElementsTrue": {
"$map": {
"input": "$CheckList.v",
"as": "cl",
"in": {
"$or": [
{
"$and": [
{
"$eq": [
"NA",
"$$cl.Status"
]
},
{
"$eq": [
"",
"$$cl.Comments"
]
}
]
},
{
"$eq": [
"OPEN",
"$$cl.Status"
]
}
]
}
}
}
}
}
},
{
"$set": {
"CheckList": {
"$arrayToObject": "$CheckList"
}
}
}
])
附注您应该将
CheckList
对象存储为数组,而不是像 this 这样的单个对象。然后,您可以避免涉及数组对象转换的复杂聚合,并通过索引获得潜在的性能提升。