0
votes

I have just upgraded mongodb from 2.4 to 2.6. Now when I run the query

$hospitals=$qb->select('distance','title','date','photos','description')
                ->field('coordinates')
                ->near((float)$lat, (float)$lng)
                ->limit(9)
                ->getQuery()
                ->execute()
                ->toArray();

distance is always null.
is this a bug or something ?
PS:$lat & $lng are OK!

2
Does it return something in previous version? Also why not to try actually mongoshell? - Salvador Dali
I'm using the mongodb Doctrine ODM, it works fine with geoNear, but not with near.. - Aysennoussi
Ahh! The format changed recently. See docs.mongodb.org/manual/reference/glossary/… - bjori

2 Answers

1
votes

I assume your model has the distance field annotated with @Distance. This only works with the geoNear command. I've updated ODM's documentation in PR #851, so that change should be reflected on the main website within a day or two.

For some reason, the documentation stated that this worked with the near() query builder method, which uses MongoDB's $near query operator. That's incorrect, as the $near operator does not return a calculated distance. Alvin mentioned using the $meta projection operator, but geoNearDistance is currently an undocumented feature in the server (only textScore is publicly documented).

Based on your original example code, the following should work:

$hospitals = $qb->select('title', 'date', 'photos', 'description')
                ->geoNear( (float) $lat, (float) $lng )
                ->limit(9)
                ->getQuery()
                ->execute()
                ->toArray();

field() is only needed with $near. geoNear() (i.e. the geoNear command) will use whatever location field is included in the geospatial index. Also, you do not need to project the distance field, since it is injected by ODM after the result comes back from MongoDB. Also, your documents in MongoDB should never actually have a distance field stored within them. See Builder::execute() for the exact code involved in populating the distance field.

0
votes

In the shell you would do something like

t = db.test
t.insert({_id: 0, loc: [0,0]})
t.insert({_id: 0, loc: [1,1]})
t.ensureIndex({loc: "2d"})
t.find({loc: {$near: [0,0]}}, {dist: {$meta: "geoNearDistance"}})

Which results in

{ "_id" : 0, "loc" : [  0,  0 ], "dist" : 0 }
{ "_id" : 1, "loc" : [  1,  1 ], "dist" : 1.4142135623730951 }