It is not possible to base MongoDB queries on values in the collections, as a general rule.
However, since MongoDB 2.4 introduced support for a new index called 2dsphere
, it is now possible to store polygons in addition to points in the database. This can be achieved by storing the information in a document like this:
db.so.ensureIndex( { loc: '2dsphere' } );
db.so.insert( {
name: "Firestation 1",
loc: {
type: "Polygon",
coordinates: [ [ [ 0, 0 ], [ 0, 1 ], [ 1, 1 ], [ 1, 0 ], [ 0, 0 ] ] ]
}
} );
You can then use an "intersect" query to determine if a point falls within any of the stored polygons:
db.so.find( {
'loc' : {
$geoIntersects: {
$geometry: { type: 'Point', coordinates: [ 0, 0 ] }
}
}
} );
The result of this query will show whether the point falls within a polygon, such as:
{
"_id" : ObjectId("51f24d566775068ab0b786f0"),
"name" : "Firestation 1",
"loc" : {
"type" : "Polygon",
"coordinates" : [ [ [ 0, 0 ], [ 0, 1 ], [ 1, 1 ], [ 1, 0 ], [ 0, 0 ] ] ]
}
}
To create a circle that is a certain distance away from the centre point, you would need to calculate the polygon points. The mathematics involved may not be simple, but resources like provide examples in JavaScript. By looping through bearings and calculating points along the circumference of the circle, you can construct a polygon with multiple points:
{
name: "Firestation 1",
loc: {
type: "Polygon",
coordinates: [ [
[ point1-lon, point1-lat ],
[ point2-lon, point2-lat ],
[ point3-lon, point3-lat ],
...
[ point1-lon, point1-lat ],
] ]
}
}