Ariel Weinberger
Ariel Weinberger

Reputation: 581

Mongoose grab a document for certain distance from a latitude-longitude coordinate

I am trying to load a document in Mongoose if it's let's say 10 kilometers from a current lat/lon coordinate.

So let's say I have this object:

{
    lat: -33.9493992,
    lon: 151.1114885
}

And in my Mongoose database I have a collection and every document within this collection also has the save lat-lon keys. How can I only grab entries of a certain distance from a given coordinate?

So for example I want to grab only the documents that are up to 10 kilometers distant from the above coordinate.

I would appreciate any help.

EDIT: My code:

Initializing the model:

var schema = new mongoose.Schema({
title: String,
    title: String,
    coordinates: {
        type: [ Number ],
        default: [0, 0],
        index: '2dsphere'
    }
});

global.models.Point = mongoose.model('Point', schema);

And the code trying to find in the model: router.route('/points/:lat/:lon') .get(function (req, res) { console.log('lat: ' + req.params.lat + ' lon:' + req.params.lon);

        global.models.Point.find({
            coordinates: {
                $near: {
                    $maxDistance: 100 / 111.12,
                    $geometry: {
                        type: 'Point',
                        coordinates: [req.params.lon, req.params.lat]
                    }
                }
            }
        }, function (err, res) {
            if (err) {
                return console.log(err);
            }
            console.log(res);
        });
    }); 

The object as it is stored in the database collection:

{ 
    "_id" : ObjectId("56ea103eefedec96b6d4b203"), 
    "title" : "Some title", 
    "coordinates" : [
        5.2260167, 
        52.3500607
    ]
}

Upvotes: 0

Views: 691

Answers (1)

oleh.meleshko
oleh.meleshko

Reputation: 4795

In your schema you need to have a field defined as following:

location: { 
  type: [ Number ], 
  default: [ 0, 0 ], 
  index: '2dsphere' 
}

Then you can do search operations on it like that:

Model.find({
  location: {
    $near: {
      $maxDistance: 100/111.12, // 100km
      $geometry: { 
        type: "Point", 
        coordinates: [151.1114885, -33.9493992] // [lon, lat]    
      }
    }
  }
}).exec(callback);

Explanation note for $maxDistance:

1° latitude = 69.047 miles = 111.12 kilometers

Upvotes: 0

Related Questions