dprfe04886 2014-10-27 06:56
浏览 132
已采纳

如何在mongodb中比较浮点值?

I have a collection name myplace having place_name(string), latitude(float64) and longitude(float64). Now I have a latitude 12.34567, I need to search mongodb is this latitude is present there or not. I tried like this but its returning null

 db.myplace.find({"latitude":12.3456})
  • 写回答

2条回答 默认 最新

  • doukekui0914 2014-10-27 07:22
    关注

    It is generally a bad idea to compare floating point values for equality, since the rounding that occurs in various floating point operations can cause certain values you'd expect to be equal to have slightly different values.

    A better solution is to check that the difference between the two floating point values is less than a particular error margin E. For this kind of query, the check becomes a range check e.g. that:

    12.3456 - E < latitude < 12.3456 + E
    

    As described in this question, this kind of query can be represented with mgo as:

    lat := 12.3456
    E := 0.0001
    q := c.Find(bson.M{"latitude": bson.M{"$gt": lat - E, "$lt": lat + E}})
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?