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

如何在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条)

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料