我有一个包含以下结构的文档的集合:
{
"foo": [
{
"bar": [
{
"baz": [
1,
2,
3
]
},
{
"baz": [
4,
5,
6
]
}
]
},
{
"bar": [
{
"baz": [
7,
8,
9
]
},
{
"baz": [
10,
11,
12
]
}
]
}
]
}
我想得到一个包含所有“条形”数组中所有值的平面数组。换句话说,我想要的结果看起来像[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
我该怎么办?
答案 0 :(得分:3)
您可以使用$reduce
运算符
db.collection.aggregate([
{ "$project": {
"array": {
"$reduce": {
"input": {
"$reduce": {
"input": "$foo",
"initialValue": [],
"in": { "$concatArrays": ["$$this.bar", "$$value"] }
}
},
"initialValue": [],
"in": { "$concatArrays": ["$$this.baz", "$$value"] }
}
}
}}
])
或使用$unwind
运算符
db.collection.aggregate([
{ "$unwind": "$foo" },
{ "$unwind": "$foo.bar" },
{ "$unwind": "$foo.bar.baz" },
{ "$group": {
"_id": "$_id",
"array": {
"$push": "$foo.bar.baz"
}
}}
])