为什么以下mongodb组查询总是返回0?

时间:2016-02-03 16:47:09

标签: mongodb aggregation-framework

我有以下示例json,它似乎并不太难。 基本上我试图通过算法字段对所有对象进行分组,然后从$ difference.close字段计算平均值。

以下是示例对象

{
    "_id" : ObjectId("56b0c702c783c42f504f006c"),
    "symbol" : "ALSK",
    "algorithm" : "AvgForecaster",
    "date" : "2016-02-01",
    "real_quote" : {
        "trade_date" : "2016-02-01",
        "open" : "1.6",
        "close" : "1.59",
        "low" : "1.57",
        "high" : "1.66",
        "volume" : "65600",
        "symbol" : "ALSK",
        "adjusted_close" : "1.59"
    },
    "forecasted_quote" : {
        "trade_date" : "2016-02-01",
        "open" : "0.0",
        "close" : "1.92",
        "low" : "0.0",
        "high" : "0.0",
        "volume" : "0",
        "symbol" : "ALSK",
        "adjusted_close" : "0.0"
    },
    "difference" : {
        "trade_date" : "2016-02-01",
        "open" : "1.6",
        "close" : "-0.33",
        "low" : "1.57",
        "high" : "1.66",
        "volume" : "65600",
        "symbol" : "ALSK",
        "adjusted_close" : "1.59"
    }
}

然后查询如下:

db.getCollection('Accuchecks').aggregate([
{
    $group: {
        _id: "$algorithm",
        accuracy: {$avg: "$difference.close"}
     }
}])

然后我得到以下结果:

{
    "result" : [ 
        {
            "_id" : "DeltaForecaster",
            "accuracy" : 0.0000000000000000
        }, 
        {
            "_id" : "AvgForecaster",
            "accuracy" : 0.0000000000000000
        }
    ],
    "ok" : 1.0000000000000000
}

查询是否没有选择$ difference.close字段?在完整的集合中,该值几乎从不为0。

由于

1 个答案:

答案 0 :(得分:1)

您将返回0,因为您将close值存储为字符串而不是浮点数。汇总管道中没有可用的类型转换功能,因此您必须将值存储为数值,请参阅此post了解如何更改现有数据的类型。

{
    "_id" : ObjectId("56b0c702c783c42f504f006c"),
    "symbol" : "ALSK",
    "algorithm" : "AvgForecaster",
    "date" : "2016-02-01",
    "real_quote" : {
        "trade_date" : "2016-02-01",
        "open" : 1.6,
        "close" : 1.59,
        "low" : 1.57,
        "high" : 1.66,
        "volume" : 65600,
        "symbol" : "ALSK",
        "adjusted_close" : 1.59
    },
    "forecasted_quote" : {
        "trade_date" : "2016-02-01",
        "open" : 0.0,
        "close" : 1.92,
        "low" : 0.0,
        "high" : 0.0,
        "volume" : 0,
        "symbol" : "ALSK",
        "adjusted_close" : 0.0
    },
    "difference" : {
        "trade_date" : "2016-02-01",
        "open" : 1.6,
        "close" : -0.33,
        "low" : 1.57,
        "high" : 1.66,
        "volume" : "65600",
        "symbol" : "ALSK",
        "adjusted_close" : .59
    }
}