Mongodb:如何“扁平化"一些查询结果 [英] Mongodb: how to "flatten" some query results

查看:207
本文介绍了Mongodb:如何“扁平化"一些查询结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在查询中帮助弄平"(与文档字段处于同一级别的嵌套字段)mongodb文档

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

我的查询:

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

预期结果:

{
    ,"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
}

推荐答案

您可以使用 $ concat 一起使用动态串联值:

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

蒙戈游乐场

这篇关于Mongodb:如何“扁平化"一些查询结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆