简体   繁体   English

获取Mongoose聚合数据总量

[英]Get the total amount of aggregated data in Mongoose

I have 2 documents: Locations and Orders我有 2 个文件: LocationsOrders

Let's say I have 4 locations, and some locations contain orders.假设我有 4 个位置,有些位置包含订单。

I'm already able to get a list of my locations with the corresponding orders for each location.我已经能够获取我的位置列表以及每个位置的相应订单。

What I'm not able to do, is to include the amount of orders for each location, and the total expanses.我不能做的是包括每个位置的订单数量和总面积。 (Each individual order already contain this information) (每个单独的订单已包含此信息)

Here's Mongo Playground with my current code.这是带有我当前代码的 Mongo Playground。 Notice that I want to populate "amount" and "total".请注意,我想填充“金额”和“总计”。

https://mongoplayground.net/p/FO_nYDOD1kn https://mongoplayground.net/p/FO_nYDOD1kn

This is what I use to aggregate my data:这是我用来聚合我的数据的内容:

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"
        }
    }
}])

and the structure of a single order:以及单个订单的结构:

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

Alright, I made something work!好吧,我做了一些工作! Yay!好极了!

Here's the solution for whoever finds this.这是找到这个的人的解决方案。

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
        })
      })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM