gpt4 book ai didi

mongodb如何查询sum字符串?

转载 作者:IT老高 更新时间:2023-10-28 13:37:48 33 4
gpt4 key购买 nike

我在 order 文档中有一些数据,例如:

{ "_id": "...", "orderTotal": { "amount" : "10.99", "unit": "USD"}, "orderTime": "...", ... }
{ "_id": "...", "orderTotal": { "amount" : "9.99", "unit": "USD"}, "orderTime": "...", ... }
{ "_id": "...", "orderTotal": { "amount" : "8.99", "unit": "USD"}, "orderTime": "...", ... }

我想按天查询所有订单组的orderTotal:

db.getCollection('order').aggregate([
{
'$group' : {
'_id': { day: { $dayOfMonth: "$orderTime"}, month: {$month: "$orderTime"}, year: { $year: "$orderTime" }},
'totalAmount': { $sum: '$itemTotal.amount' },
'count': { $sum: 1 }
}
}
])

但是得到了:

{
"_id" : {
"day" : 12,
"month" : 12,
"year" : 2016
},
"totalAmount" : 0,
"count" : 4607.0
}

amount 是一个字符串。使用 parseFloat 但得到了 NaN。

db.getCollection('order').aggregate([
{
'$group' : {
'_id': { day: { $dayOfMonth: "$orderTime"}, month: {$month: "$orderTime"}, year: { $year: "$orderTime" }},
'totalAmount': { $sum: parseFloat('$itemTotal.amount') },
'count': { $sum: 1 }
}
}
])

得到

{
"_id" : {
"day" : 12,
"month" : 12,
"year" : 2016
},
"totalAmount" : NaN,
"count" : 4607.0
}

我无法更新 order 文档以将 itemTotal.amount 更改为像其他问题所说的那样 float :

db.order.find().forEach(function(data) {
db.order.update({
"_id": data._id,
"itemTotal.amount": data.itemTotal.amount
}, {
"$set": {
"itemTotal.amount": parseFloat(data.itemTotal.amount)
}
});
})

我无权执行此操作。那么,我怎样才能得到按天计算的总和呢?

最佳答案

这在 MongoDB 3.4 中是不可能的。此功能已被请求,但尚未实现:

Need a type conversion mechanism to convert between strings and numbers

所以解决您的问题的唯一方法是在javascript中手动执行totalAmount sum ...


编辑

现在可以在 MongoDB 4.0 中实现从一种类型转换为另一种类型的运算符,例如 $toDouble

所以查询将是:

db.collection.aggregate([
{
"$group": {
"_id": null,
"totalAmount": {
"$sum": {
"$toDouble": "$orderTotal.amount"
}
},
"count": {
"$sum": 1
}
}
}
])

你可以在这里试试:mongoplayground.net/p/4zJTPU912Es

关于mongodb如何查询sum字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41119461/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com