使用$slice、$map 和$arrayElemAt:
{ "$project": {
"foo": {
"$ifNull": [
{ "$arrayElemAt": [
{ "$map": {
"input": { "$slice": [
{ "$map": {
"input": { "$slice": [ "$bar", 0, 1 ] },
"as": "el",
"in": "$$el.baz"
}},
0, 1
]},
"as": "el",
"in": { "$arrayElemAt": [ "$$el.qux", 0 ] }
}},
0
]},
"*"
]
}
}}
因此,内部 $map 运算符允许您从每个数组中选择特定字段,您可以在所需位置 $slice 以仅返回该元素。即0,1 是零索引,只有一个元素。
对于最终结果数组,您只需使用 $arrayElemAt 并检索索引元素,将其转换为单个值。
当然,$ifNull 测试可能需要更多参与,具体取决于您的结构,如果它不一致,那么您可能需要检查每个 $map 输入并相应地交换结果。
但大体流程是:
-
$map 获取字段
-
$slice 从$map 减少数组
-
$arrayElemAt 在最终数组结果中。
关于这样的事情:
db.foo.insert({
"bar": [
{
"baz": [
{ "qux": 2 },
{ "qux": 5 }
]
},
{
"baz": [
{ "qux": 3 },
{ "qux": 4 }
]
}
]
})
生产:
{ "_id" : ObjectId("56e8c6b8ff2a05c0da90b31e"), "foo" : 2 }