none
none

Reputation: 1817

MongoDB and Geo Query

I have a collection of documents in which there are two important fields for me: srcCoordinates and dstCoordinates. They look like this:

"dstCoordinates" : {
    "latitude" : 46.46647770314815,
    "longitude" : 30.642414093017578
}

What type of index I must add, to be able to search for all documents within a radius of a given point? Radius - in meters!

I want to do something like this:

db.collection.find({dstCoordinates: {$near:[46.46647770314815, 30.642414093017578], $maxDistance: 1000}})

1000 - distance in meters!

In general, the question is: how do I find all points within 1000 meters, for example?

Upvotes: 0

Views: 478

Answers (2)

Raj Jaril
Raj Jaril

Reputation: 376

Geo query with latitude, longtitude, radius - Find place from database

var geolocation = new Array(-26.90, 50.70 ); // lng, lat
PlacesAPI.aggregate(
            [
            {"$geoNear":
            {"near": {"type":"Point","coordinates": geolocation },
            "spherical":true,
            "distanceField":"distance",
            "maxDistance": 50000
            }
         },
            { $project : {
                    _id:0,
                    name: "$name",
                    details: "$details",
                    distance: "$distance",
                }
            }
            ],function (err, result) {
console.log(result)
})

Upvotes: 0

Anand Jayabalan
Anand Jayabalan

Reputation: 12944

You'll need to create a geospatial index on the "dstCoordinates" field for the $near queries to work. An example query to create a 2d index:

db.collection.ensureIndex({"dstCoordinates":"2d"})

After the index is created, your find() query should work fine.

Note: For storing location information, array are preferred in MongoDB. That is:

loc : [ longitude , latitude ]

is preferred over

loc : { lng : longitude , lat : latitude }

Also, you'll need to store the co-ordinates in longitude, latitude order

Upvotes: 1

Related Questions