Mongo DB - Geospatial Queries with location and field radius(Internal field comparision)
You can use the $where
operator:
model.find({'$where': function() { var myLoc = [ 14.67, 56.78 ]; return { 'loc': { '$geoWithin': { "$centerSphere": [ myLoc, this.Radius ] } } }}})
Sample collection data
{ "business": "Store","geo": { "name": "StoreName", "coordinates": [80.628913, 13.622177], "type": "Point"},"address": "Some Address","city": "Kolkata","pincode": "700001","startTime": "10:00:00 AM","closingTime": "7:00:00 PM","closedOn": "Closed on Sunday",}
Create 2dSphear index on db.collectionName.createIndex({geo:'2dsphere'})
Now use the $geoNear aggregation query to smoothly fetch record.
db.collectionName.aggregate([ { $geoNear: { near: { type: "Point", coordinates: [ 80.3355,13.6701 ] }, // Mandatory Param. distanceField: "dist.calculated", // It will return in the document how much distence (meter) is far feom center maxDistance: 2000, // Fetch 2KM radius store, Distance in meter from the center spherical: true, // calculates distances using spherical geometry. query:{pincode:"700001"} // Specific Query parameter on other field present in the collection } } ]).pretty()
This is a working code and tested and verified.