Geolocation MongoDB Node.js


I was wondering if there were any examples that consisted of a basic geolocation entry and database retrieval of given entries in a certain area, preferably the current location of the user.

The answer

Here is a quick overview of geospatial queries in MongoDB:

You must insert location information into your collection via a 2D array

 db.example.insert( {"location": [x,y], "category": "restaurant"}) 

Configure geospatial indexes on the collection by specifying the location field with the "2d" option.

 db.example.ensureIndex( { "location" : "2d" } ) 

Now the collection will have a clue on which all geospatial queries will be made against.

To find locations near a point (ie, the current location of the user), use the find () command with $near operand on the location field indicating the coordinates of the points (c to 100, 100).

 db.example.find( { "location": { $near : [100, 100] } } ) 

To find the current location of users, you should need higher-level application support to get the current user information.

For more information:

MongoDB Documentation:

The operator $near :