mongodb $avg aggregation calculation out by a few decimals.

时间:2018-03-13 15:09:50

标签: mongodb aggregation-framework average

We have a collection in Mongodb which saves a value linked to a timestamp.

Our document looks as follows (I have pasted an actual one here):

{
    "_id" : ObjectId("5a99596b0155fe271cfcf41d"),
    "Timestamp" : ISODate("2018-03-02T16:00:00.000Z"),
    "TagID" : ObjectId("59f8609eefbb4102f4c249e3"),
    "Value" : 71.3,
    "FileReferenceID" : ObjectId("000000000000000000000000"),
    "WasValueInterpolated" : 0
}

What we then do is calculate the avg between two intervals for a given period, in more basic terms, work out an aggregated profile.

The aggregation code we use is:

    {[{ "$match" : 
    { 
        "TagID" : ObjectId("59f8609eefbb4102f4c249e3") } 
    }, 
    { 
        "$match" : { "Timestamp" : { "$gte" : ISODate("2018-03-12T00:00:00.001Z") } } 
    }, 
    {
        "$match" : { "Timestamp" : { "$lte" : ISODate("2018-03-13T00:00:00.001Z") } } 
    }, 
    { 
        "$group" : 
        { 
            "_id" : { "GroupedMillisecond" : 
                    { 
                        "$let" : 
                        { 
                            "vars" : 
                            { "newMillisecondField" : 
                            { 
                                "$subtract" : ["$Timestamp", ISODate("2018-03-12T00:00:00.001Z")] 
                            } 
                            }, 
                            "in" : { "$subtract" : ["$$newMillisecondField", { "$mod" : ["$$newMillisecondField", NumberLong(1800000)] }] } 
                        } 
                    } }, "AverageValue" : { "$avg" : "$Value" } 
        } 
    }, { "$sort" : { "_id.GroupedMillisecond" : 1 } }
]}

The problem is this, the value it should give back is 71.3, but we get back 71.299999999999997

In this case, I posted above we are calculating the avg value, half hourly aggregated, for a day. And there is only one value per half hour logged (I checked this in the database). The value is also logged as a constant, as far back as I manually checked (a few months back) it is 71.3

So my question is why does the value differ?

0 个答案:

没有答案