Reputation: 3860
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!
Upvotes: 0
Views: 265
Reputation: 6922
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.
Upvotes: 1
Reputation: 141
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 }
Upvotes: 0