1fabiopereira 1fabiopereira - 11 months ago 79
Node.js Question

Mongoose geolocation query

I have documents with the following format in a bundle of mongdb data:

{
"_id": "5839f170ca31803284785ef3",
"name": "Alex",
"coordinates": {
"type": "point",
"coordinates": [
-23.073889,
-44.96
]
},
"__v": 0
}


I would like to execute a query where I enter the latitude and longitude of the center point and the size of the radius and the answer is all the users that are within that radius.

I'm starting with mongoose and have no idea how to do this query ?

Answer Source

Try this:

db.collection.find({
  'coordinates.coordinates': {
    $geoWithin: {
      $center: [[<x>, <y>], radius]
    },
  },
});

Ref: https://docs.mongodb.com/manual/reference/operator/query/center/