简体   繁体   中英

Get the total amount of aggregated data in Mongoose

I have 2 documents: Locations and Orders

Let's say I have 4 locations, and some locations contain orders.

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. Notice that I want to populate "amount" and "total".

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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