How to get array from mongoDB collection?

2019-01-20 14:24发布

问题:

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?

回答1:

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
}


回答2:

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" ]