在聚合框架的上下文中,并考虑存储在 MongoDB 集合中的以下简化文档结构:
[
{ 'reference': 'ReferenceStr',
'subgroup': [ { '#': 1, 'param': 123},
{ '#': 2, 'param': 456},
{ '#': 3, 'param': 789}
],
'group': [ {'#': 1, 'start': 1, 'end': 2},
{'#': 2, 'start': 3, 'end': 3} ],
}
]
知道 $group.# 上的条件(假设 $group.#=1),我想使用 $group.end 的关联值(此处为 2)来获取与 $subgroup 对应的 $subgroup.param 的值。 #=$group.end
我想返回: {'参考':'ReferenceStr','var':456}
到目前为止我只有:
db_collection.aggregate([
{ '$project' : {
'reference' : '$reference',
'var' : {
...
}
}
}
])
$indexOfArray 和 $arrayElementAt 是我唯一的希望吗? 我迷失在结构中。
如有任何帮助,我们将不胜感激。
您可以通过
$lookup
在您指定的组中使用end
进行自我查找。然后在子管道中,可以通过$match
$group.end
过滤出期望的子组。
db.collection.aggregate([
{
"$unwind": "$group"
},
{
// input your group condition here
$match: {
"group.#": 1
}
},
{
"$lookup": {
"from": "collection",
"let": {
"end": "$group.end"
},
"pipeline": [
{
"$unwind": "$subgroup"
},
{
"$match": {
$expr: {
$and: [
// find the subgroup that matches your condition
{$eq: [
"$$end",
"$subgroup.#"
]
}
]
}
}
}
],
"as": "selfLookup"
}
},
{
"$unwind": "$selfLookup"
},
{
$project: {
_id: 0,
reference: "$selfLookup.reference",
var: "$selfLookup.subgroup.param"
}
}
])
这里是Mongo游乐场供您参考。