Search code examples
mongodbgomgo

How can I compare a float value in 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})

Solution

  • 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}})