MongoDB:聚合和展平数组字段 [英] MongoDB: Aggregate and flatten an array field

查看:70
本文介绍了MongoDB:聚合和展平数组字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用关系数据库(SQL Server,MySQL,Oracle,Informix)28年之后,我搬到了MongoDB.在过去的两周里进展缓慢.我想提出几个问题以确认我的想法.

After 28 years working with relational databases (SQL Server, MySQL, Oracle, Informix) I have moved to 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"}
    ]
}

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

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 (e.g., '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.

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

I am currently using MongoDB 3.2

推荐答案

从MongoDb 3.4开始,我们可以使用

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.

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 }

这篇关于MongoDB:聚合和展平数组字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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