【问题标题】:How to merge multiples MongoDB documents into one?如何将多个 MongoDB 文档合并为一个?
【发布时间】:2017-12-19 02:01:49
【问题描述】:

我正在处理从物联网设备不断收到的一组测量值。每个度量都有以下文档架构:

{
    "_id" : ObjectId("58e3c885713c09001a0c2125"),
    "recvTime" : ISODate("2017-04-18T16:23:38.928Z"),
    "entityId" : "t01",
    "entityType" : "Thing",
    "attrName" : "Temperature",
    "attrType" : "text",
    "attrValue" : "32.5"
}

根据设备的编程方式,对于设备的每个属性,我都有不同的测量值。由于设备每 N 秒发送一次数据,因此每 N 秒插入与我设备中的属性一样多的文档。在“recvTime”字段中具有相同时间的所有文档。

我的问题是我想在单个文档中折叠与特定时间对应的所有测量数据。这样,我每 N 秒就有一个包含所有设备测量值的文档,而不是像我的设备上的属性一样多的文档。

例如,有两个属性 temperaturepreassure 我想转换这个:

{
    "_id" : ObjectId("58e3c885713c09001a0c2125"),
    "recvTime" : ISODate("2017-04-18T16:23:38.928Z"),
    "entityId" : "t01",
    "entityType" : "Thing",
    "attrName" : "Temperature",
    "attrType" : "text",
    "attrValue" : "32.5"
},
{
    "_id" : ObjectId("58e3c885713c09001a0c2125"),
    "recvTime" : ISODate("2017-04-18T16:23:38.928Z"),
    "entityId" : "t01",
    "entityType" : "Thing",
    "attrName" : "Preassure",
    "attrType" : "text",
    "attrValue" : "512"
}

变成这样:

{
    "_id" : ObjectId("58e3c885713c09001a0c2125"),
    "recvTime" : ISODate("2017-04-18T16:23:38.928Z"),
    "entityId" : "t01",
    "entityType" : "Thing",
    "Temperature" : "32.5",
    "Preassure" : "512"
}

有没有办法只使用 Mongo 聚合框架的查询来做到这一点?我宁愿不必在应用程序中执行此操作。

提前致谢。

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    您可以在 3.6 中使用以下聚合。

    $group 将所有相同时间戳的文档与$$ROOT 分组到$push 完整文档。

    $objectToArray$filter 过滤需要重命名的键,然后在 $reduce 运算符中使用 $mergeObjects$arrayToObject 来合并分组文档。

    $replaceRoot 将合并的文档提升到顶层。

    [{"$group":{
       "_id":"$recvTime",
       "data":{"$push":"$$ROOT"}
    }},
    {"$replaceRoot":{
       "newRoot":{
         "$reduce":{
           "input":"$data",
           "initialValue":{},
           "in":{
             "$mergeObjects":[
               {"$arrayToObject":{
                 "$filter":{
                   "input":{"$objectToArray":"$$this"},
                   "cond":{"$not":{"$in":["$$this.k",["attrName","attrValue","attrType"]]}}
                 }
               }},
               {"$arrayToObject":[[{"k":"$$this.attrName","v":"$$this.attrValue"}]]},
               "$$value"
               ]
           }
         }
       }
    }}]
    

    【讨论】:

    • 谢谢!我会试试你的建议,
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 2013-08-23
    • 1970-01-01
    • 2017-10-17
    相关资源
    最近更新 更多