【问题标题】:Convert embedded documents into separate documents in mongodb将嵌入文档转换为mongodb中的单独文档
【发布时间】:2021-12-27 13:14:49
【问题描述】:

我有以下文件。

[
  {
    "content": {
      "abc123": {
        "_id": "abc123",
        "total": 189,
        "published": 189,
        "created": 0,
        "approved": 0,
        "rejected": 0,
        "sent_for_approval": 0
      },
      "abc124": {
        "_id": "abc124",
        "total": 1911,
        "published": 1899,
        "created": 10,
        "approved": 2,
        "rejected": 0,
        "sent_for_approval": 0
      }
    }
  },
  {
    "content": {
      "abc124": {
        "_id": "abc124",
        "total": 1911,
        "published": 1899,
        "created": 10,
        "approved": 2,
        "rejected": 0,
        "sent_for_approval": 0
      }
    }
  }
]

如何将这个键值对对象转换成单独的文档,如下所示,不重复enter code here:

[
  {
    "_id": "abc123",
    "total": 189,
    "published": 189,
    "created": 0,
    "approved": 0,
    "rejected": 0,
    "sent_for_approval": 0
  },
  {
    "_id": "abc124",
    "total": 1911,
    "published": 1899,
    "created": 10,
    "approved": 2,
    "rejected": 0,
    "sent_for_approval": 0
  }
]

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    查询

    • 将对象转换为数组
    • 展开并替换根(因此每个嵌入的文档都是一个单独的根文档)
    • 按键分组,只保留第一个删除重复项
    • 替换 root 以获得预期的输出

    Test code

    aggregate(
    [{"$set":{"content":{"$objectToArray":"$content"}}},
     {"$unwind":"$content"},
     {"$replaceRoot":{"newRoot":"$content"}},
     {"$group":{"_id":"$k", "doc":{"$first":"$v"}}},
     {"$replaceRoot":{"newRoot":"$doc"}}])
    

    【讨论】:

      猜你喜欢
      • 2016-02-23
      • 1970-01-01
      • 2012-04-22
      • 1970-01-01
      • 2021-02-21
      • 1970-01-01
      • 1970-01-01
      • 2018-08-21
      • 1970-01-01
      相关资源
      最近更新 更多