MongoDB Aggregation -显示所有子文档以及父文档中的一些信息

xriantvc  于 2022-12-22  发布在  Go
关注(0)|答案(1)|浏览(166)

我的invoices集合如下所示:

[
  {
    inv_name: "Client 1",
    inv_date: 2022-12-20T05:09:09.803Z,
    inv_ready: false,
    inv_payments: [
      {
        id: "123",
        pay_amount: 32.45
      },
      {
        id: "456",
        pay_amount: 55.60
      }
    ]
  },
  {
    inv_name: "Client 2",
    inv_date: 2022-12-19T05:09:09.803Z,
    inv_ready: true,
    inv_payments: [
      {
        id: "459",
        pay_amount: 67.45
      },
      {
        id: "556",
        pay_amount: 30.60
      }
    ]
  }
]

我知道如何使用$project$unwind创建一个子文档数组,目标是像这样从父文档向每个对象添加一些数据。

[
  {
    "client": "Client 1",
    "pay_amount": 32.45,
    "pay_date": "123"
  },
  {
    "client": "Client 1",
    "pay_amount": 55.6,
    "pay_date": "456"
  },
  {
    "client": "Client 2",
    "pay_amount": 67.45,
    "pay_date": "459"
  },
  {
    "client": "Client 2",
    "pay_amount": 30.6,
    "pay_date": "556"
  }
]

下面是我的尝试:

db.invoices.aggregate([
  {
    "$project": {
      _id: 0,
      "inv_payments": {
        $reduce: {
          input: "$inv_payments",
          initialValue: [],
          in: {
            $concatArrays: [
              [
                {
                  client: "$this.name",
                  pay_id: "$$this.id",
                  pay_amount: "$$this.pay_amount"
                }
              ],
              "$inv_payments"
            ]
          }
        }
      }
    }
  },
  {
    $unwind: "$inv_payments"
  },
  {
    $replaceRoot: {
      newRoot: "$inv_payments"
    }
  }
])

我想我已经接近了。我不确定错误在哪里。任何想法都将不胜感激!

6vl6ewon

6vl6ewon1#

除了注解中提到的打字错误,你使用$reduce操作符的方式也不正确,你没有使用累加器变量($$value)。
不要使用$reduce,而是使用$map运算符,这在您的场景中更为简单:

溶液1:$map

{
  "$project": {
    _id: 0,
    "inv_payments": {
      $map: {
        input: "$inv_payments",
        in: {
          client: "$inv_name",
          pay_date: "$$this.id",
          pay_amount: "$$this.pay_amount"
        }
      }
    }
  }
}

Demo ( $map ) @ Mongo Playground

解决方案2:$reduce

对于$reduce运算符,您的查询应为:

{
  "$project": {
    _id: 0,
    "inv_payments": {
      $reduce: {
        input: "$inv_payments",
        initialValue: [],
        in: {
          $concatArrays: [
            [
              {
                client: "$inv_name",
                pay_date: "$$this.id",
                pay_amount: "$$this.pay_amount"
              }
            ],
            "$$value"
          ]
        }
      }
    }
  }
}

Demo ( $reduce ) @ Mongo Playground

相关问题