user644745
user644745

Reputation: 5713

mongodb: can find on a 2d index return distance?

i see from the mongodb doc, that db.runCommand with geoNear return distance also.

I am using mongoose in node.js and want to know if the same can be achieved with Model.find({'loc': { $near: [lng, lat], $maxDistance:5/111.12},.....)

runCommand with geoNear does not work if you have more than one 2d index. I have 2 2d index in a collection. One defined in the schema and the other one is part of a DbRef.

Also I'm not very comfortable about the exact syntax to be used for runcommand with mongoose.

Upvotes: 1

Views: 1282

Answers (1)

christkv
christkv

Reputation: 4430

geoNear, which is available in the native MongoDB driver and therefore by extension in mongoose, will search all geo indexes in the document and can there for return it multiple times you can pass the parameter uniqueDocs to ensure you have no duplicate entries.

collection.geoNear(50, 50, {uniqueDocs:true}, function(err, docs) {
});

The alternative is to do a near query on a specific field but you might have to do some conversion of the distance value to get the right range. I don't remember off the top of my mind what that would be. The best place to experiment is the mongoshell and then just translate it to a command for node.js.

Upvotes: 1

Related Questions