mongodb如何查询sum字符串?

时间:2016-12-13 11:00:27

标签: mongodb

我在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更改为浮动,就像其他问题所说:

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

我没有权限这样做。 那么,我怎样才能在白天得到这笔钱?

1 个答案:

答案 0 :(得分:5)

从MongoDB 3.4开始,这是不可能的。此功能已被请求,但尚未实施:

Need a type conversion mechanism to convert between strings and numbers

因此,解决问题的唯一方法是在javascript中手动执行totalAmount总和...

修改

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

所以查询将是:

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

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