Martin Spriggs
Martin Spriggs

Reputation: 35

MongoDB number precision using $lt and $gt

I'm having trouble getting MongoDB to return documents when using (I am assuming) different precision queries.

Here is a sample record in my DB:

{"P_Latitude": "32.896272727272", "P_Longitude": "-109.8293454545"}

Here is a sample query that returns no documents:

{
    "P_Latitude": {
        "$gt": "32.097473448554915",
        "$lt": "33.45585495144508"
    },
    "P_Longitude": {
        "$lt": "-110.0001001",
        "$gt": "-99.9999999"
    }
}

However, when I change the last $gt to a number greater than -100 it works...like:

{
    "P_Latitude": {
        "$gt": "32.097473448554915",
        "$lt": "33.45585495144508"
    },
    "P_Longitude": {
        "$lt": "-110.0001001",
        "$gt": "-100.9999999"
    }
}

Is this a precision issue, or something else? It behaves the same in the shell and using the Monk driver.

Thanks!!!

Upvotes: 1

Views: 471

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311925

The problem is that you're storing your P_Latitude and P_Longitude values as strings instead of numbers. As a result, the comparisons are performed using lexical order instead of numeric order.

Your docs should look like this instead:

{"P_Latitude": 32.896272727272, "P_Longitude": -109.8293454545}

And queried like this:

{
    "P_Latitude": {
        "$gt": 32.097473448554915,
        "$lt": 33.45585495144508
    },
    "P_Longitude": {
        "$gt": -110.0001001,
        "$lt": -99.9999999
    }
}

Upvotes: 1

Related Questions