Thursday, 1 June 2017

Mongo Create 2dsphere index with longitude and latitude in separate document fields

I'm wanting to create a 2dsphere index on a mongo db table in which documents have latitude and longitude stored in different numerical fields:

var myModel = new Schema({
  latitude: Number,
  longitude: Number
})

However, all of the examples I've seen build indices on a single field in the table that contains both the latitude and longitude of each document, like this (these specific examples come from this SO question):

var userSchema = new Schema({
  loc: {
    type: { type: String },
    coordinates: [Number],
  }
});

userSchema.index({ "loc": "2dsphere" });
var User = mongoose.model( "User", userSchema );

Given that schema, one can query the index like this:

User.aggregate(
    [
        { "$geoNear": {
            "near": {
                "type": "Point",
                "coordinates": [<long>,<lat>]
            },
            "distanceField": "distance",
            "sperical": true,
            "maxDistance": 10000
        }}
    ],
    function(err,results) {}
)

Is it possible to achieve something similar in the case where latitude and longitude are stored in separate fields within a document? I'd be very grateful for any advice others can offer on this question!



via duhaime

No comments:

Post a Comment