【问题标题】:How to merge two fields into one field in MongoDB如何在MongoDB中将两个字段合并为一个字段
【发布时间】:2020-05-03 13:54:36
【问题描述】:

以下是产品集合示例文档:

{ _id:'xxxxxxxxxxxx',
  name:'product 1'
 }
{ _id:'xxxxxxxxxxxx',
  name:'product 2'
 }

如何在mongodb中将id字段值分组为name字段值?

预期结果:

[{'xxxxxxxxxxxx:'product1'},{'xxxxxxxxxxxx':'product2'}]

【问题讨论】:

  • 预期结果是什么?
  • _id 的类型是什么如果它是ObjectId() 类型你不能这样做你需要将它转换为字符串才能做到这一点因为键不持有@987654325 @的..

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

您可以尝试以下聚合查询:

在 MongoDB 版本上 >= 4.2:

db.collection.aggregate([
  {
    $replaceWith: {
      $arrayToObject: [
        [
          {
            k: { $toString: "$_id" },
            v: "$name"
          }
        ]
      ]
    }
  }
])

测试: mongoplayground

在 MongoDB 版本上 >= 4.0

db.collection.aggregate([
  {
    $replaceRoot: {
      newRoot: {
        $arrayToObject: [
          [
            {
              k: { $toString: "$_id" },
              v: "$name"
            }
          ]
        ]
      }
    }
  }
])

测试: mongoplayground

以防万一您有更多字段并希望在最终结果中保留文档中的所有字段,然后在 MongoDB 版本上尝试此操作 >= 4.0

db.collection.aggregate([
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [
          {
            $arrayToObject: [ [ { k: { $toString: "$_id" }, v: "$name" } ] ]
          },
          "$$ROOT"
        ]
      }
    }
  }
])

测试: mongoplayground

注意:因为对象中的键必须是 string 类型,并且不能保存 ObjectId() 类型,我们将 _id 值转换为 string,如果您的 @ 987654335@ 是字符串类型,则无需使用$toString 运算符。

参考:aggregation-pipeline-stages

【讨论】:

    猜你喜欢
    • 2016-09-17
    • 2016-09-17
    • 2013-10-20
    • 1970-01-01
    • 2014-02-27
    • 2015-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多