Reputation: 227
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?
Upvotes: 6
Views: 6235
Reputation: 61225
This is a straightforward query. The distinct()
method will beautifully get the job done.
db.collection.distinct("regions.cities.name")
which produces:
[ "luga", "moskva", "piter", "tula" ]
Upvotes: 8
Reputation: 103365
Run the following aggregation pipeline :
db.collection.aggregate([
{ "$unwind": "$regions" },
{ "$unwind": "$regions.cities" },
{
"$group": {
"_id": null,
"cities": { "$push": "$regions.cities.name" }
}
}
])
Sample Output
{
"result" : [
{
"_id" : null,
"cities" : [
"moskva",
"tula",
"piter",
"luga"
]
}
],
"ok" : 1
}
Upvotes: 4