我们说我有一组对象:
{
_id : 1,
list1 : [
{ name: 'This is my name', value: 'This is my value' },
{ name: 'name number 2', value: 'value number 2' }
],
list2 : [
{ name: 'Another name', value: 'Another value' }
],
deeper : {
list3 : [
{ name: 'Another name but even deeper', value: 'Another value but deeper' }
]
}
}
使用聚合管道如何返回单个名称/值对象列表? 结果应该是:
{
_id : 1,
combinedList : [
{ name: 'This is my name', value: 'This is my value' },
{ name: 'name number 2', value: 'value number 2' },
{ name: 'Another name', value: 'Another value' },
{ name: 'Another name but even deeper', value: 'Another value but deeper' }
]
}
第2部分:
现在,如何将整个集合中的深层嵌套对象展平为单个响应?例如:
{
"_id" : 0,
list1 : [
{ name: 'This is my name', value: 'This is my value' },
{ name: 'name number 2', value: 'value number 2' }
],
list2 : [
{ name: 'Another name', value: 'Another value' }
]
},
{
"_id" : 1,
list1 : [
{ name: 'This is my name', value: 'This is my value' },
{ name: 'name number 2', value: 'value number 2' }
],
deeper : {
list2 : [
{ name: 'Another name but even deeper', value: 'Another value but deeper' }
]
}
}
结果应该与上面的文档相同(combinedList)。
答案 0 :(得分:1)
您可以使用aggregate
和setUnion
db.coll.aggregate([
{
$match:{_id:1}
},
{
$project: {_id: 0 ,
combinedList: { $setUnion: [ "$deeper.list3","$list2", "$list1" ] }}
}
]
)
结果
{
"result" : [
{
"combinedList" : [
{
"name" : "Another name but even deeper",
"value" : "Another value but deeper"
},
{
"name" : "Another name",
"value" : "Another value"
},
{
"name" : "name number 2",
"value" : "value number 2"
},
{
"name" : "This is my name",
"value" : "This is my value"
}
]
}
],
"ok" : 1
}
http://docs.mongodb.org/manual/reference/operator/aggregation/setUnion/
你必须使用2.6版本。