是否可以展平 MongoDB 结果查询?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13281733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to flatten MongoDB result query?
提问by Marsellus Wallace
I have a deeply nested collection in my MongoDB collection.
我的 MongoDB 集合中有一个深度嵌套的集合。
When I run the following query:
当我运行以下查询时:
db.countries.findOne({},{'data.country.neighbor.name':1,'_id':0})
I end up with this nested result here:
我最终得到了这个嵌套结果:
{"data" : {
"country" : [
{
"neighbor" : [
{
"name" : "Austria"
},
{
"name" : "Switzerland"
}
]
},
{
"neighbor" : {
"name" : "Malaysia"
}
},
{
"neighbor" : [
{
"name" : "Costa Rica"
},
{
"name" : "Colombia"
}
]
}
]
}}
Now, this is what I want:
现在,这就是我想要的:
['Austria', 'Switzerland', 'Malaysia', 'Costa Rica', 'Colombia']
or this:
或这个:
{'name':['Austria', 'Switzerland', 'Malaysia', 'Costa Rica', 'Colombia']}
or anything else similar... Is this possible?
或其他类似的东西......这可能吗?
回答by RameshVel
You can use $project
& $unwind
& $group
of aggregationframework to get the result closer to your requirement.
您可以使用$project
& $unwind
& $group
of聚合框架来使结果更接近您的要求。
> db.countries.aggregate({$project:{a:'$data.country.neighbor.name'}},
{$unwind:'$a'},
{$unwind:'$a'},
{$group:{_id:'a',res:{$addToSet:'$a'}}})
{
"result" : [
{
"_id" : "a",
"res" : [
"Colombia",
"Malaysia",
"Switzerland",
"Costa Rica",
"Austria"
]
}
],
"ok" : 1
}
$unwind
used twice since the name array is nested deep. And It will only work if the neighbor
attribute is an array. In your example one neighbor field (Malaysia) is not an array
$unwind
由于名称数组嵌套很深,因此使用了两次。并且仅当neighbor
属性是数组时才有效。在您的示例中,一个邻居字段(马来西亚)不是数组
回答by wadouk
Done it much simpler way, maybe it is recent
以更简单的方式完成,也许是最近的
db.countries.aggregate({$unwind:'$data.country.neighbor.name'})
回答by James Gan
It's pretty straightforward under the new aggregation framework. The $project and $unwind operation are right for the purpose.
在新的聚合框架下非常简单。$project 和 $unwind 操作就是为了这个目的。