Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get array from 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?

like image 344
Ростислав Падалко Avatar asked Mar 12 '23 19:03

Ростислав Падалко


1 Answers

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" ]
like image 71
styvane Avatar answered Mar 20 '23 06:03

styvane