Node.js 获取Mongoose中聚合数据的总量

Node.js 获取Mongoose中聚合数据的总量,node.js,mongoose,Node.js,Mongoose,我有两个文档:位置和订单 假设我有4个位置,有些位置包含订单 我已经能够得到我的位置列表,以及每个位置对应的订单 我不能做的是,包括每个地点的订单数量和总面积。(每个订单已经包含此信息) 这是Mongo游乐场和我的当前代码。 请注意,我想填充“amount”和“total” 这是我用来聚合数据的方法: db.Locations.aggregate([{ $lookup: { from: "Orders", let: { loc_i

我有两个文档:
位置
订单

假设我有4个位置,有些位置包含订单

我已经能够得到我的位置列表,以及每个位置对应的订单

我不能做的是,包括每个地点的订单数量和总面积。(每个订单已经包含此信息)

这是Mongo游乐场和我的当前代码。 请注意,我想填充“amount”和“total”

这是我用来聚合数据的方法:

db.Locations.aggregate([{
    $lookup: {
        from: "Orders",
        let: {
            loc_id: "$_id"
        },
        pipeline: [{
            $match: {
                $expr: {
                    $eq: ["$$loc_id", "$location"]
                }
            }
        }, {
            $project: {
                _id: 0,
                products: 1
            }
        }],
        as: "orders"
    }
}, {
    $project: {
        _id: 1,
        name: 1,
        orders: {
            total: "insert total orders expanses in this order",
            amount: "insert amount of orders for this location",
            orders: "$orders"
        }
    }
}])
以及单一订单的结构:

{
  "_id": "5e17ab585eb7f11a971bce5c",
  "location": "5e17a001f1e0220def7a2b5d",
  "total": "1000"
}

好吧,我做了点事!耶

不管是谁找到了这个,这里都有解决办法

Location
.aggregate([
        {
          $lookup: {
            from: "orders",
            let: { loc_id: "$_id" },
            pipeline: [{ $match: { $expr: { $eq: ["$$loc_id", "$location"] } } }],
            as: "order"
          }
        }

        ,
        {
          $project: {
            _id: 1,
            name: 1,
            address: 1,
            orders: {
              total: { $sum: "$order.total" },
              amount: { $size: "$order" },
              items: "$order"
            }
          }
        }
      ])
      .then(locations => {
        res.status(200).json({
          success: true,
          locations
        })
      })
      .catch(error => {
        res.status(500).json({
          success: false,
          error
        })
      })