我有一个这样的文件:

{
  'name': 'douglas'
  'datetime_created': '2019-10-24',
  'datetime_expiration': '2019-01-12'
}

我想将此文档拆分为两个文档,分别是 datetime_createddatetime_expiration 字段。
预期输出:
{
  'name': 'douglas'
  'datetime_created': '2019-10-24'
},
{
  'name': 'douglas'
  'datetime_expiration': '2019-01-12'
}

我怎样才能用 aggregation 做到这一点?

最佳答案

分3步:

创建包含 2 个项目 + $unwind + $replaceRoot$replaceWith 的数组

db.collection.aggregate([
  {
    $project: {
      data: [
        {
          name: "$name",
          datetime_created: "$datetime_created"
        },
        {
          name: "$name",
          datetime_expiration: "$datetime_expiration"
        },

      ]
    }
  },
  {
    $unwind: "$data"
  },
  {
    $replaceRoot: {
      newRoot: "$data"
    }
  }
])

MongoPlayground

关于mongodb - 根据两个字段将文档拆分为两个文档(带聚合),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59900551/

10-12 00:30
查看更多