如何从mongoDB集合中获取数组? [英] How to get array from mongoDB collection?
本文介绍了如何从mongoDB集合中获取数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在mongoDB中有这样的架构
i have such schema in mongoDB
{
"key":"ru",
"regions":[
{
"name":"moskovskaya",
"cities":[
{
"name":"moskva"
},
{
"name":"tula"
}
]
},
{
"name":"piterskaya",
"cities":[
{
"name":"piter"
},
{
"name":"luga"
}
]
}
]
}
我有一些针对不同国家/地区的此类架构的文档, 如何从该架构的每个文档中获取所有城市的数组?
i have some documents of such schema for different countries, how can i get an array of ALL cities from each document of this schema?
推荐答案
运行以下聚合管道:
db.collection.aggregate([
{ "$unwind": "$regions" },
{ "$unwind": "$regions.cities" },
{
"$group": {
"_id": null,
"cities": { "$push": "$regions.cities.name" }
}
}
])
示例输出
{
"result" : [
{
"_id" : null,
"cities" : [
"moskva",
"tula",
"piter",
"luga"
]
}
],
"ok" : 1
}
这篇关于如何从mongoDB集合中获取数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文