Arrays mongodb,如何使用聚合在嵌套数组上投影或推送根字段?
下面的示例文档有四个嵌套数组Arrays mongodb,如何使用聚合在嵌套数组上投影或推送根字段?,arrays,mongodb,mongodb-query,aggregation-framework,Arrays,Mongodb,Mongodb Query,Aggregation Framework,下面的示例文档有四个嵌套数组 { "_id" : ObjectId("5ed6bd9596908c36f4200980"), "attr2" : "hello", "attr3" : 1234, "attr1" : { "firstArray" : [ { "secondArray" : [ { "seco
{
"_id" : ObjectId("5ed6bd9596908c36f4200980"),
"attr2" : "hello",
"attr3" : 1234,
"attr1" : {
"firstArray" : [
{
"secondArray" : [
{
"secondAttr1" : "world",
"secondAttr2" : 456,
"secondAttr3" : [
{
"finalArray" : [
{
"finalAttr1" : "alex",
"finalAttr2" : 9876
}
]
}
]
}
]
}
]
}
}
这个聚合查询通过嵌套数组进行查找,为处理的每个数组展开并创建新的根,从“finalArray”返回元素
此聚合的结果为
{
"finalAttr1" : "alex",
"finalAttr2" : 9876
}
我的问题是,如何在所有聚合阶段投射根字段“attr2”,使其位于结果数组中
{
"attr2" : "hello",
"finalAttr1" : "alex",
"finalAttr2" : 9876
}
我是mongo的新手,对此我完全不知所措,所以非常感谢您的帮助
顺便说一下,我正在使用Mongo3.4.15
非常感谢 在您的情况下,您只需要在MongoDB版本
3.4
中引入的$addFields
:
我已经减少了几个似乎没有用的阶段和操作符,请检查这个最新的聚合管道:
db.collection.aggregate([
{
"$match": { "attr2": "hello" }
},
/** This stage adds new field to the place where you want */
{
$addFields: { "attr1.firstArray.secondArray.secondAttr3.finalArray.attr2": "$attr2" }
},
{
"$unwind": "$attr1.firstArray"
},
{
"$replaceRoot": { "newRoot": "$attr1.firstArray" }
},
{
"$project": {
"secondArray": {
"$filter": { "input": "$secondArray", "cond": { "$eq": [ "$$this.secondAttr1", "world" ] } }
}
}
},
{
"$unwind": "$secondArray"
},
{
"$replaceRoot": { "newRoot": "$secondArray" }
},
{
"$unwind": "$secondAttr3"
},
{
"$replaceRoot": { "newRoot": "$secondAttr3" }
},
{
"$project": {
"finalArray": { "$filter": { "input": "$finalArray", "cond": { "$eq": [ "$$this.finalAttr1", "alex" ] } } }
}
},
{
"$unwind": "$finalArray"
},
{
"$replaceRoot": { "newRoot": "$finalArray"}
}
])
测试:
Ref:
注意:
$和
(请参阅第一阶段)在您的情况下,您只需要在MongoDB版本
3.4
中引入的$addFields
:
我已经减少了几个似乎没有用的阶段和操作符,请检查这个最新的聚合管道:
db.collection.aggregate([
{
"$match": { "attr2": "hello" }
},
/** This stage adds new field to the place where you want */
{
$addFields: { "attr1.firstArray.secondArray.secondAttr3.finalArray.attr2": "$attr2" }
},
{
"$unwind": "$attr1.firstArray"
},
{
"$replaceRoot": { "newRoot": "$attr1.firstArray" }
},
{
"$project": {
"secondArray": {
"$filter": { "input": "$secondArray", "cond": { "$eq": [ "$$this.secondAttr1", "world" ] } }
}
}
},
{
"$unwind": "$secondArray"
},
{
"$replaceRoot": { "newRoot": "$secondArray" }
},
{
"$unwind": "$secondAttr3"
},
{
"$replaceRoot": { "newRoot": "$secondAttr3" }
},
{
"$project": {
"finalArray": { "$filter": { "input": "$finalArray", "cond": { "$eq": [ "$$this.finalAttr1", "alex" ] } } }
}
},
{
"$unwind": "$finalArray"
},
{
"$replaceRoot": { "newRoot": "$finalArray"}
}
])
测试:
Ref:
注意:
$和
(请参阅第一阶段)谢谢你,很好用。谢谢你的留言,我需要和mongo再打一场;)谢谢你,很好用。谢谢你的留言,我需要和mongo再打一场;)