MongoDB:聚合并展平数组字段

时间:2016-11-27 21:09:45

标签: mongodb

使用关系数据库(SQL Server,MySQL,Oracle,Informix)28年后,我已转移到MongoDB。过去两周一直很缓慢。我想提出几个问题来证实我的想法。

我的文档如下所示(忽略此问题的分组):

{
    "_id": "xyz-800",
    "site": "xyz",
    "user": 800,
    "timepoints": [
        {"timepoint": 0, "a": 1500, "b": 700},
        {"timepoint": 2, "a": 1000, "b": 200},
        {"timepoint": 4, "a": 3500, "b": 1500}
    ],
    "groupings": [
        {"type": "MNO", "group": "<10%", "raw": "1"},
        {"type": "IJK", "group": "Moderate", "raw": "23"}
    ]
}

我想展平嵌套数组的时间点。以下是有效的,但是有没有办法在时间点中对属性进行通配符而不是列出每个属性?原因可能是如果将新属性(例如,'c')添加到子文档中,则必须修改代码,或者如果此子文档具有许多属性,我需要列出每个属性而不是使用通配符,如果可能的。

db.records.aggregate( {$unwind : "$timepoints"}, 
                      {$project: {_id: 1, site: 1, user: 1, 
                                  'timepoint': '$timepoints.timepoint', 
                                  'a': '$timepoints.a', 
                                  'b': '$timepoints.b'}})

结果:

{"id":"xyz-800", "site":"xyz", "user":800, "timepoint": 0, "a":1500, "b":700}
{"id":"xyz-800", "site":"xyz", "user":800, "timepoint": 2, "a":1000, "b":200}
{"id":"xyz-800", "site":"xyz", "user":800, "timepoint": 4, "a":3500, "b":1500}

我目前正在使用MongoDB 3.2

1 个答案:

答案 0 :(得分:2)

启动MongoDb 3.4,我们可以使用 $addFields 将顶级字段添加到嵌入式文档中,并使用 $replaceRoot < / strong>将嵌入式文档推广到顶级。

db.records.aggregate({
    $unwind: "$timepoints"
}, {
    $addFields: {
        "timepoints._id": "$_id",
        "timepoints.site": "$site",
        "timepoints.user": "$user"
    }
}, {
    $replaceRoot: {
        newRoot: "$timepoints"
    }
})

示例输出

{ "timepoint" : 0, "a" : 1500, "b" : 700, "_id" : "xyz-800", "site" : "xyz", "user" : 800 }
{ "timepoint" : 2, "a" : 1000, "b" : 200, "_id" : "xyz-800", "site" : "xyz", "user" : 800 }
{ "timepoint" : 4, "a" : 3500, "b" : 1500, "_id" : "xyz-800", "site" : "xyz", "user" : 800 }