upanisad
upanisad

Reputation: 21

PHP, Mongo query using or and dot notation

I've a problem that's getting me crazy!

I need to translate the following Mongo query in PHP:

db.mycollection.find({$or: [ {'field.a': 45.4689, 'field.b': 9.18103}, {'field.a' : 40.71455, 'field.b': -74.007124} ]})

It works perfectly from the shell.

I think the query should be translated to PHP in the following way (var_dump):

Array
    (
        [$or] => Array
            (
                [0] => Array
                    (
                        [field.a] => 45.468945
                        [field.b] => 9.18103
                    )

                [1] => Array
                    (
                        [field.a] => 40.71455
                        [field.b] => -74.007124
                    )

            )

    )

but I get no results in PHP!

Why? What's wrong? What's the correct syntax?

Thank you!

Upvotes: 2

Views: 815

Answers (1)

Derick
Derick

Reputation: 36784

Your syntax seems fine to me, I think the main problem is is that you are using floating point numbers which are not always as accurate as you think—especially if you mix up 45.4689 and 45.468945 yourself. For direct comparing of floating point numbers, you should always add a small fuzzing factor.

In this case you seem to be using coordinates? If that's the case, I suggest you:

  • swap the a and b fields (so that you get longitude, then latitude)
  • create a 2d index on "field": ensureIndex( array( 'field' => '2d' ) );
  • use geoNear with a small max distance and a limit of 1,

That should give a much better way of scanning for points. You'd have to run the query twice though, as the geoNear command can't do $or.

If you only have a discrete set of points (like your comments seems to indicate), then I would recommend to not query on floating point numbers but simply add a field naming the city as well.

Upvotes: 3

Related Questions