如何在保存到根目录时压平 mongo db 中的对象并有条件重命名字段?

问题描述 投票:0回答:1

我有一个集合,其中包含需要展平的余额对象,并且该对象中的字段需要根据集合中的另一个标志进行重命名 -

[
  {
    "id": "1234",
    "documentType": "IV",
    "balance": {
      "total": 100,
      "openBalance": 60,
      "paid": 40
    }
  },  
  {
    "id": "9012",
    "documentType": "CM",
    "balance": {
      "total": 50,
      "applied": 0,
      "available": 50
    }
  }
]

如果 documentType === "IV",则 $$ROOT 中的 "balance.paid" 将变为 "totalAmountPaid",而如果是 "CM",则 "balance.applied" 将重命名为 AppliedAmount 和 "balance.available" " 为 availableAmount,所以压平余额对象后最终的集合就变成了 -

[
  {
    "id": "1234",
    "documentType": "IV",
    "total": 100,
    "openBalance": 60,
    "totalAmountPaid": 40
  },  
  {
    "id": "9012",
    "documentType": "CM",
    "total": 50,
    "appliedAmount": 0,
    "availableAmount": 50
  }
]

我尝试像这样使用 $set 和 $cond 但它不起作用,而且我对 MongoDB 命令不是很熟悉 -

db.collection.aggregate([
  {
    $set: {
      $cond: {
        if: {
          $eq: [
            "$documentType",
            "IV"
          ]
        },
        then: {
          "total": "$balance.total",
          "openBalance": "$balance.openBalance",
          "totalAmountPaid": "$balance.paid",
          "balance": "$$REMOVE"
        },
        else: {
          "$total": "$balance.total",
          "$availableAmount": "$balance.available",
          "$appliedAmount": "$balance.applied",
          "balance": "$$REMOVE"
        }
      }
    }
  }
])

mongodb aggregation-framework
1个回答
0
投票

您在

$set
中面临的问题是因为您试图在一个字段中创建多个字段(新对象),并且您没有提供名称。

由于您要创建多个新字段,因此首先将它们创建为一个字段中的子对象然后用该子对象替换原始文档会更容易。

(此外,在您的

else
子句中,您使用
$total
作为字段名称,而不仅仅是
total
。)

需要改变:

  1. 在查询的第一部分中,给出字段的名称
    newdoc
    并且该表达式包含您之前的代码。
    • 并且您不需要
      "balance": "$$REMOVE"
      ,因为无论如何它都会被
      newdoc
      取代
  2. 然后将主文档的 id 和 documentType 字段与新创建的文档合并,因为主文档中已经有 其他字段
  3. 还有
    $unset
    不需要的
    balance
    字段和子
    newdoc
    字段。
db.collection.aggregate([
  {
    $set: {
      newdoc: {
        $cond: {
          if: { $eq: ["$documentType", "IV"] },
          then: {
            "total": "$balance.total",
            "openBalance": "$balance.openBalance",
            "totalAmountPaid": "$balance.paid"
          },
          else: {
            "total": "$balance.total",
            "availableAmount": "$balance.available",
            "appliedAmount": "$balance.applied"
          }
        }
      }
    }
  },
  { $replaceWith: { $mergeObjects: ["$$ROOT", "$newdoc"] } },
  { $unset: ["balance", "newdoc"] }
])

蒙戈游乐场

(以前的 Mongo 游乐场)

© www.soinside.com 2019 - 2024. All rights reserved.