簡體   English   中英

獲取Mongoose聚合數據總量

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

我有 2 個文件: LocationsOrders

假設我有 4 個位置,有些位置包含訂單。

我已經能夠獲取我的位置列表以及每個位置的相應訂單。

我不能做的是包括每個位置的訂單數量和總面積。 (每個單獨的訂單已包含此信息)

這是帶有我當前代碼的 Mongo Playground。 請注意,我想填充“金額”和“總計”。

https://mongoplayground.net/p/FO_nYDOD1kn

這是我用來聚合我的數據的內容:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM