Search code examples
javascriptnode.jsmongodbgeolocation

mongo near set maxDistance as value in collection


I am sorry by the title. I was hard to describe. I have this collection

  {
      "_id" : ObjectId("55cb9c666c522cafdb053a68"),
      location: {
     type: "Point",
     coordinates: [-73.856077, 40.848447]
  },
      "maxDistancevalue" : 100000
  }

Now I want to find of the current location is within: 100000 as defined is the collection by "maxDistancevalue"

The code will be like this. But how set the maxDistancevalue?

  db.places.find(
     {
       location:
         { $near :
            {
              $geometry: { type: "Point",  coordinates: [ -73.9667, 40.78 ] },
              $minDistance: **??????, -->maxDistancevalue** 
              $maxDistance: 0
            }
         }
     }
  ) 

Solution

  • You can use Aggregation Framework's $geoNear pipeline stage to reference other existing field. It requires 2dsphere index to be created on your collection, so start with:

    db.places.createIndex({location:"2dsphere"});
    

    and then you can run your aggregate() query:

    db.places.aggregate([
        {
            $geoNear: {
                near: { type: "Point", coordinates: [ -73.9667, 40.78 ] },
                distanceField: "dist.calculated",
                maxDistance: "$maxDistancevalue"
            }
        }
    ])