我有以下查询:
cursor=self.postCol.aggregate([
{ "$graphLookup" : {
"from": "pCol",
"startWith": "$parent",
"connectFromField": "parent",
"connectToField": "_id",
"as" : "parents"
}
},
{ "$project" : {
"pValue": {
"$cond": [
{ "$ne": [ "$pValue", [] ] },
"$pValue",
"$parents.0.pValue"
]
}
}
}
])
因此给出以下记录:
{"_id": 4, parent: "", "pValue": ["d"], fieldA: 9},
{"_id": 5, parent: 4, "pValue": [], fieldA:2},
{"_id": 6, parent: 4,"pValue": [], fieldA: 9}
我应该得到:
{"_id": 4, "pValue": ["d"]}
{"_id": 5, "pValue": ["d"]}
{"_id": 6, "pValue": ["d"]}
相反,我得到:
{"_id": 4, "pValue": ["d"]}
{"_id": 5, "pValue": []}
{"_id": 6, "pValue": []}
由于某种我不明白的原因,$parents.0.pValue
没有返回正确的值。如何在父数组的第一个元素中选择 pValue
字段?
我想使用 {"$arrayElemAt": ["$parents",0]}
这将为我提供嵌入文档,但是我怎样才能从中获取要返回的字段?
最佳答案
您可以使用 $let
运算符将 else 条件替换为以下条件。
{
$let: {
vars: {
obj: {
"$arrayElemAt": ["$parents", 0]
}
},
in: "$$obj.pValue"
}
}
关于mongodb - 嵌入数组中嵌入文档中的项目字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41695271/