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条)

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)