mongodb 如何将文档分组到其他模型的数组中

How to group documents into an array of other model in mongodb

由于我是 mongodb 的新手并且 nodejs 我被困在这里,我有一个索赔集合,每个索赔都有一个 orderId 作为字段,我想做的是将所有按订单 ID 声明并将它们显示在订单数组中,例如我有这些声明:

[
    {
        message: "claim1",
        orderId: 123456789
    },
    {
        message: "claim2",
        orderId: 0000000
    },
    {
        message: "claim3",
        orderId: 123456789
    },
    {
        message: "claim4",
        orderId: 0000000
    }
]

我想做的是按顺序对这些声明进行分组,我发现我可以在互联网上搜索时使用 $group 来完成,但困难的部分是我希望结果是一个订单数组,该数组的每个案例都包含一些订单字段和该订单的索赔数组。这就是我想要的结果:

[
    {
        orderId: 123456789,
        orderNumber: "OrderNumber"
        // i want to get this from the order document in the database,
        claims: [
            {
                message: "claim1"
            },
            {
                message: "claim2"
            }
        ]
    },
    {
        orderId: 00000000,
        orderNumber: "OrderNumber"
        // i want to get this from the order document in the database,
        claims: [
            {
                message: "claim2"
            },
            {
                message: "claim4"
            }
        ]
    }
]

这是一个订单示例:

{
 _id:123456789,
  orderNumber:112,
  orderPrice:14,
  created_at: 2020-04-29T16:34:48.522+00:00
  updated_at: 2020-05-01T14:03:04.844+00:00
}

我一直在寻找解决方案,但找不到任何解决方案,我开始认为 mongodb 聚合可能无法实现。感谢您的帮助

所以我们的策略是首先 $group on the orderId to gather all the claims, and then we'll $lookup 订单号,如下所示:

db.collection.aggregate([
  {
    $group: {
      _id: "$orderId",
      claims: {
        $push: {
          message: "$message"
        }
      }
    }
  },
  {
    "$lookup": {
      "from": "orders",
      "localField": "_id",
      "foreignField": "_id",
      "as": "orders"
    }
  },
  {
    $unwind: "$orders"
  },
  {
    $project: {
      _id: 0,
      claims: 1,
      orderId: "$_id",
      orderNumber: "$orders.orderNumber"
    }
  }
])