How to implement location-based search results using MongoDB

Hi Reader, there are multiple ways of implementing the location-based search results, In this, we are going to see how to implement it with Geospatial queries in MongoDB.

  • Firstly, in order to query from MongoDB based on the location, we need to have the details of the coordinates in collection (table) entries. It should be in GeoJSON format. All the entries should have this field.

GeoJSON format to be added in Schema during the creation of Schema:

{
    /* other fields & their types */
    location : {
        type: Object,
        index : "2dsphere",
        required : true
    }
}

GeoJSON format to be added in entries while inserting into the collection:

{
    /* other fields & their data */ 
    "location" : {
        "type" : "Point",
        "coordinates" : [
            // latitude here,
            // longitude here
        ]
    }
}

Note : There are multiple "type", here we go with "point". If you want to know more about all "type" in detail click here.

  • We are half done, Remaining is the querying part. While querying we need the coordinates for making it location-based. So, the request data must contain the location coordinates.
db./*collection_name*/.find({
    location : {
        $nearSphere : {
            $geometry : {
                type : "Point",
                coordinates : [
                    // latitude here (from request body),
                    // longitude here (from request body)  
                ]
            },
            $maxDistance : //distance in meter
        }
    }
})

Note : "maxDistance" is to set the boundary for searching. Results will be in the ascending order of distance from the given coordinates up to maximum distance set.

And yes, we are done with our job. Hope this helps you.