首页 > 解决方案 > 将数组内的不同数量的值相乘:Mongodb

问题描述

我已经安排了我的数据,以便将属于同一客户 ID 的文档聚合到一个集合中。数据格式如下。

{
"items": [
    {
        "stock_code": [
            "22617",
            "22768",
            "20749"
        ],
        "description": [
            "DESIGN",
            "FAMILY PHOTO FRAME",
            "ASSORTED CASES"
        ],
        "quantity": [
            18,
            12,
            84
        ],
        "unit_price": [
            4.95,
            9.95,
            6.35
        ]
    }
],
"_id": 581485,
"customer_id": 17389,
"country": "United Kingdom"
}

我需要将数组数量的值与相应的 unit_price 相乘,并获得一个新字段中多个文档的总数。我曾尝试使用 $reduce 函数和 $map 函数来获取输出,但它们都导致“错误”

乘法只支持数值类型,不支持数组

你能否建议我应该如何去完成这个。

代码尝试:

"$addFields": {"order_total" : 
                 { 
            "$sum": { 
                "$map": { 
                    "input": "$items", 
                    "as": "items", 
                    "in": { "$multiply": [ 
                        { "$ifNull": [ "$$items.quantity", 0 ] }, 
                        { "$ifNull": [ "$$items.unit_price", 0 ] } 
                     ]} 
                    }
                } 
              }
            }

第二:

"order_total" : {
            "$reduce" : {
                "input" : "$items",
                "initialValue" : Decimal128("0.00"),
                "in": {
                    "$sum" : [
                        "$$value",
                        {"$multiply" : [ "$$this.quantity", "$$this.unit_price" ] }
                    ]}
             }
       }

预期的结果需要通过将unit_price的对应条目乘以数量来添加一个新的“total”字段。错误消息是multiply 仅支持数字类型而不支持数组

标签: databasemongodb

解决方案


试试下面的查询:

db.collection.aggregate(
[{ $unwind: { path: "$items",} }, 
{ $unwind: {  path: "$items.quantity",} }, 
{ $unwind: {  path: "$items.unit_price",} }, 
{ $addFields: { 'total': {$multiply:   ["$items.quantity", "$items.unit_price"]  }} }])

推荐阅读