【问题标题】:$group with $map not working properly in mongodb$group 和 $map 在 mongodb 中无法正常工作
【发布时间】:2021-05-24 19:20:37
【问题描述】:

我是 mongodb 聚合的新手,我有一个集合

{
"_id":60ab3312623b0108338a9601,
"items":[{"type":"Tshirt","price":300,"quantity":2}],
"orderId":"ORD189",
"from":"abc",
"to":"xyz",
"createdAt":2021-05-24T05:01:06.960Z,
"__v":0,
"tracking":null
}

我想查找每天的订单数量和类似物品的总价格

{_id: {date:24, month:05, year:2021}, count: 1, totalPrice: 600}

我使用了像下面这样的聚合


db.getCollection("orders").aggregate(
    [
        { 
            "$group" : { 
                "_id" : { 
                    "date" : { 
                        "$dayOfMonth" : "$createdAt"
                    }, 
                    "month" : { 
                        "$month" : "$createdAt"
                    }, 
                    "year" : { 
                        "$year" : "$createdAt"
                    }
                }, 
                "count" : { $sum : 1},
                "totalPrice" : { 
                    $sum: {
                        $map: {
                            "input" :"$items",
                            "as":"item",
                            "in":{
                                $multiply: ["$item.price", "$item.quantity"]
                            }
                        }
                    }
                }
            }
        }
    ]
);

它给了我以下结果

{ 
    "_id" : {
        "date" : NumberInt(24), 
        "month" : NumberInt(5), 
        "year" : NumberInt(2021)
    }, 
    "count" : 1.0, 
    "totalPrice" : NumberInt(0)
}

如果我使用 unwind 无法获得正确的计数。

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    你只需要更正totalPrice的计算,

    • $map 迭代 items 的循环并对 pricequantity 进行乘法运算,这将返回总计数组
    • $sum 获取以上总数
    "totalPrice": {
      $sum: {
        $sum: {
          $map: {
            input: "$items",
            in: {
              $multiply: ["$$this.price", "$$this.quantity"]
            }
          }
        }
      }
    }
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-06
      • 2020-10-20
      • 2021-03-17
      • 1970-01-01
      • 2019-08-30
      • 2018-03-10
      相关资源
      最近更新 更多