MongoDB求和查询不会进行求和

3

我有以下文件:

{ "_id" : ObjectId("5d9db4462034bf17454d7d33"), "name" : "Product1", "cost_oneoff" : "1", "cost_monthly" : "1", "margin_oneoff" : "1", "margin_monthly" : "1", "price_oneoff" : "1", "price_monthly" : "1" }
{ "_id" : ObjectId("5d9dc2f2d8e17309b46f9b03"), "name" : "Product2", "cost_oneoff" : "0", "cost_monthly" : "1", "margin_oneoff" : "0,5", "margin_monthly" : "0,5", "price_oneoff" : "0", "price_monthly" : "2" }

我希望得到以下语句中每月费用的总和,例如:


{ "_id" : null, "total" : 0 }

有人能帮我吗?

db.service_items.aggregate([
    { $match: {$or: [{"_id": ObjectId("5d9db4462034bf17454d7d33")},{"_id": ObjectId("5d9dc2f2d8e17309b46f9b03")}]}},
    { $group: 
        {_id: null,
        total: {
            $sum: "$cost_monthly"
            }
        }
    }
])

结果:

{ "_id" : null, "total" : 0 }

期望的答案是2。
2个回答

2

$sum 运算符仅适用于整数。根据 文档,它会忽略非数字值。您似乎将它们存储为字符串。将 cost_monthly 更改为整数,您应该可以获得所需的结果:

"cost_monthly" : 1

你可以在这里查看。


1

像 @silencedogood 所说的那样,$sum 运算符只适用于整数。我们需要使用 $toInt 运算符将字符串转换为数字值。

以下是一个示例:

db.service_items.aggregate([
    { 
        $match: {
            $or: [
                {
                    "_id": ObjectId("5d9db4462034bf17454d7d33")
                },
                {
                    "_id": ObjectId("5d9dc2f2d8e17309b46f9b03")
                }
            ]
        }
    },
    { 
        $group: {
            "_id": null,
            "total": {
                 $sum: {
                    $toInt: "$cost_monthly"
                 }
            }
        }
    }
])

注意:$toInt是在Mongo v4.0中引入的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接