Mongodb: how to “flatten” some query results

怎甘沉沦 提交于 2021-01-28 18:12:06

问题


Help to "flatten" (to pull nested fields at same level as document's fields) a mongodb document in a query

//this is "anagrafiche" collection
[{
 "name": "tizio"
,"surname": "semproni"
,"birthday": "01/02/1923"
,"home": {
     "road": "via"
    ,"roadname": "bianca"
    ,"roadN": 12
        ,"city": "rome"
        ,"country": "italy"
        }
},
{
 "name": "caio"
,"surname": "giulio"
,"birthday": "02/03/1932"
,"home": {
     "road": "via"
    ,"roadname": "rossa"
    ,"roadN": 21
        ,"city": "milan"
        ,"country": "italy"
        }
},
{
 "name": "mario"
 ,"surname": "rossi"
// birthday is not present for this document
,"home": {
     "road": "via"
    ,"roadname": "della pace"
    ,"roadN": 120
        ,"city": "rome"
        ,"country": "italy"
        }
}
]

my query:

db.anagrafiche.aggregate([  {$match {"home.city": "rome"}}
                {$project:{"name": 1, "surname":1, <an expression to flatten the address>, "birthday": 1, "_id":0}}
             ]
);

expected result:

{
    ,"name": "tizio"
    ,"surname": "semproni"
    ,"address": "via bianca 12 rome"
    ,"birthday": 01/02/1923
},{
    ,"name": "mario"
    ,"surname": "rossi"
    ,"address": "via della pace 120 rome"
    ,"birthday": NULL
}

回答1:


You can use $objectToArray to get nested document keys and values and then use $reduce along with $concat to concatenate values dynamically:

db.collection.aggregate([
    {
        $project: {
            _id: 0,
            name: 1,
            surname: 1,
            birthday: 1,
            address: {
                $reduce: {
                    input: { $objectToArray: "$home" },
                    initialValue: "",
                    in: {
                        $concat: [
                            "$$value",
                            { $cond: [ { $eq: [ "$$value", "" ] }, "", " " ] },
                            { $toString: "$$this.v" }
                        ]
                    }
                }
            }
        }
    }
])

Mongo Playground



来源:https://stackoverflow.com/questions/62346889/mongodb-how-to-flatten-some-query-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!