MongoDb。展平内部阵列
我有一个包含以下结构的文档的集合:MongoDb。展平内部阵列,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,我有一个包含以下结构的文档的集合: { "foo": [ { "bar": [ { "baz": [ 1, 2, 3 ] }, { "baz": [ 4, 5, 6 ] }
{
"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]
我怎么做呢 您可以使用运算符使用下面的聚合 或使用运算符
哪一个查询速度更快$展开还是$reduce?@VikashSingh
$unwind
始终解构数组并根据数组大小创建文档副本。因此,第一个$reduce
当然是更好的选择
db.collection.aggregate([
{ "$project": {
"array": {
"$reduce": {
"input": {
"$reduce": {
"input": "$foo",
"initialValue": [],
"in": { "$concatArrays": ["$$this.bar", "$$value"] }
}
},
"initialValue": [],
"in": { "$concatArrays": ["$$this.baz", "$$value"] }
}
}
}}
])
db.collection.aggregate([
{ "$unwind": "$foo" },
{ "$unwind": "$foo.bar" },
{ "$unwind": "$foo.bar.baz" },
{ "$group": {
"_id": "$_id",
"array": {
"$push": "$foo.bar.baz"
}
}}
])