Geospatial query with variable distance / geospatial query in $where query

80 views
Skip to first unread message

glyphobet

unread,
May 9, 2011, 9:01:53 AM5/9/11
to mongodb-user
Hi. I've got another question about geospatial queries. As before, I'm
a bit of a noob, so bear with me if this is a really silly question.

I have a collection where each item has a point and a radius for which
it's relevant. I want to do a ordinary spherical query, but I want the
radius to come out of the collection as well. So I want to do a query
like this:

var earthRadius = 6378; // in km
db.points.insert({location: [-122.441, 37.762], radius:1}); // SF
db.points.insert({location: [-122.270, 37.804], radius:16}); //
Oakland
db.points.ensureIndex({location:"2d"});

db.points.find({location: {$nearSphere: [-122.441, 37.762],
$maxDistance: this.radius/earthRadius}});
db.points.find({location: {$within: {$centerSphere: [[-122.441,
37.762], this.radius/earthRadius]}}});

I'm not sure how to refer to another field in the collection from
inside the $centerSphere or $nearSphere expression, though. Do I have
to use a Javascript $where query? If so, how do I call centerSphere or
nearSphere from within a Javascript $where query?

(and yes, I know that this is likely going to be slow, but the queries
will be heavily constrained along many other dimensions, and the
$where will execute last, so it should be ok.)

-matt

Greg Studer

unread,
May 9, 2011, 10:13:57 AM5/9/11
to mongod...@googlegroups.com
Hmm... you could use two queries, or alternately can use a $where query
alongside the geospatial query, something like:

db.points.find({ loc : { $within : { $centerSphere : [[x, y], [big num
like 300]/earthRadius] } }, $where : "Geo.sphereDistance( this.loc, [x,
y] ) < this.radius" })

i'm a bit confused as to what you're trying to model though, since if
you have multiple points, potentially at the same location, I'm not sure
what document you'd want to refer to for the radius.

glyphobet

unread,
May 9, 2011, 10:47:02 AM5/9/11
to mongodb-user
Thanks! I think Geo.sphereDistance was exactly what I'm looking for.

To explain my problem a bit more, I have a collection of documents,
where each document has a location and radius that defines the area
over which that specific document is relevant. Some documents are
relevant to just a small area, and others relevant over a very large
area. I want to provide just a location, and get all the documents
that are relevant at that location.

The $where clause that you wrote with Geo.sphereDistance seems to do
exactly what I need, thanks.

-matt
Reply all
Reply to author
Forward
0 new messages