How to get array of all values of a specific field in a mongoDB collection?

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

Answers (2)

Sede
Sede

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

chridam
chridam

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

Related Questions