sanu
sanu

Reputation: 548

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

Upvotes: 3

Views: 3568

Answers (2)

James Henstridge
James Henstridge

Reputation: 43939

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

Upvotes: 4

peterSO
peterSO

Reputation: 166714

First, are you looking for (have) 12.34567 or (find) 12.3456?

Floating-point numbers are an approximation of real numbers. Look for a number in a range. For example,

(12.34567 - 0.0001) < latitude < (12.34567 + 0.0001)

References:

Floating point

Upvotes: 2

Related Questions