首页 > 解决方案 > 在 MongoDB 中的记录中取消嵌套值

问题描述

我的任务是取消 中的记录MongoDB,但不幸的是,我没有MongoDB技能。

我有以下格式的记录:

{
    "_id" : ObjectId("Some ID"),
    "reason" : "Parameter: (artifact_id) is mandatory",
    "timestamp_utc" : ISODate("2019-09-20T14:30:41.943Z"),
    "timestamp" : ISODate("2019-09-20T07:30:41.943Z"),
    "eventType" : "Some_Event",
    "clientID" : "24839961",
    "time_bucket" : [
        "2019-year",
        "2019-09-month",
        "2019-37-week",
        "2019-09-20-day",
        "2019-09-20 07-hour"
    ],
    "payload" : {
        "resWidth" : 1440,
        "resHeight" : 900,
        "device" : "",
        "context_eid" : "Some EID",
        "artifact_revision_id" : 8389171,
        "page_url" : "Some URL",
        "client_ip" : "Some IP",
        "tz" : "Asia/Calcutta",
        "memberID" : Some_ID,
        "url_referrer" : "Some_URL",
        "tabID" : "Some ID",
        "artifactID" : 5665946,
        "visitorID" : "Some ID",
        "g_event_id" : "Some ID",
        "content_data" : "Some Data",
        "sessionID" : "Some ID",
        "user_agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36"
    },
    "resolved" : false
}

请注意,这payload是它自己的字典。我必须取消嵌套该字典并将其恢复到与文档中其他键相同的级别。像这样:

{
    "_id" : ObjectId("Some ID"),
    "reason" : "Parameter: (artifact_id) is mandatory",
    "timestamp_utc" : ISODate("2019-09-20T14:30:41.943Z"),
    "timestamp" : ISODate("2019-09-20T07:30:41.943Z"),
    "eventType" : "Some_Event",
    "clientID" : "24839961",
    "time_bucket" : [
        "2019-year",
        "2019-09-month",
        "2019-37-week",
        "2019-09-20-day",
        "2019-09-20 07-hour"
    ],
    "resWidth" : 1440,
    "resHeight" : 900,
    "device" : "",
    "context_eid" : "Some EID",
    "artifact_revision_id" : 8389171,
    "page_url" : "Some URL",
    "client_ip" : "Some IP",
    "tz" : "Asia/Calcutta",
    "memberID" : Some_ID,
    "url_referrer" : "Some_URL",
    "tabID" : "Some ID",
    "artifactID" : 5665946,
    "visitorID" : "Some ID",
    "g_event_id" : "Some ID",
    "content_data" : "Some Data",
    "sessionID" : "Some ID",
    "user_agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36",
    "resolved" : false
}

我最初的研究表明$reduce可能是一种选择,但我似乎无法弄清楚。

对此主题的任何帮助将不胜感激。如果这个任务太简单而无法发布,我很抱歉,但我的MongoDB技能为零。

标签: mongodb

解决方案


您可以使用MongoDB 聚合。如果我们将顶级文档($$ROOT变量)与payload对象合并,我们会得到单个对象($mergeObjects应该分配给新变量,但我们减少了使用$ReplaceRootor进行 2 操作的管道步骤$ReplaceWith)。

db.EVENT_NAME.aggregate([
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [
          "$$ROOT",
          "$payload"
        ]
      }
    }
  },
  {
    $unset: "payload"
  }
])

Mongo游乐场


推荐阅读