GeoSpatial Indexing in MongoDB

Is DIRT simple! Consider the code, which searches an item collection for items located near a specific location, designated in longitude/latitude (according to the GeoJSON spec, longitude first, latitude second):
this.findItems = function(db, type, longitude, latitude, index, pageSize, callback){
db.collection("items",function (err, collection){
if (err) throw err;
collection.ensureIndex(["location","2d"], false, function(err){
var search = {}, paging = {};
if(type) search.type = type;
if(longitude != null && latitude != null)
search.location = {"$near" : [parseFloat(longitude),parseFloat(latitude)]};

if (index >= 0 && pageSize >= 0){
paging.skip = index*pageSize;
paging.limit = pageSize;
}

collection.find(search, paging,
function(err,cursor){
cursor.toArray(function(err,items){
callback(items);
}
);
});
});
});
}

It's that simple (minus hours of learning how to do that, scratching my head over stupid errors that I caused but didn't know I was causing [us computer scientists are quick to blame the other guy :) ])

If you can decipher that, good for you. Onto step 3 of a million on my little code project.

blog comments powered by Disqus