简体   繁体   English

MongoDB:聚合和展平一个数组字段

[英]MongoDB: Aggregate and flatten an array field

After 28 years working with relational databases (SQL Server, MySQL, Oracle, Informix) I have moved to MongoDB.在使用关系数据库(SQL Server、MySQL、Oracle、Informix)工作 28 年后,我转向了 MongoDB。 It has been slow going over the last two weeks.过去两周进展缓慢。 I would like to submit a couple of questions to confirm my thoughts.我想提交几个问题来确认我的想法。

My document looks like the following (ignore groupings for this question):我的文档如下所示(忽略此问题的分组):

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

I would like to flatten the timepoints nested array.我想展平时间点嵌套数组。 The following works, but is there a way to wildcard the attributes in timepoints instead of listing each one?以下有效,但有没有办法通配时间点中的属性而不是列出每个属性? The reason could be if a new attribute (eg, 'c') is added to the subdocument I then have to modify the code or if this subdocument had a lot of attributes I would need to list each one instead of using a wildcard, if possible.原因可能是如果将新属性(例如,'c')添加到子文档中,我必须修改代码,或者如果此子文档有很多属性,我需要列出每个属性而不是使用通配符,如果可能。

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

Result:结果:

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

I am currently using MongoDB 3.2我目前正在使用 MongoDB 3.2

Starting MongoDb 3.4, we can use $ addFields to add the top level fields to the embedded document and use $replaceRoot to promote embedded document to top level.从 MongoDb 3.4 开始,我们可以使用$ addFields将顶级字段添加到嵌入文档中,并使用$replaceRoot将嵌入文档提升到顶级。

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

Sample Output样本输出

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM