Implementing ‘Near Me’ Location-Based Searches with MongoDB: A Guide to Geospatial Queries

Girish M Saraswathipura
DataDrivenInvestor
Published in
5 min readSep 28, 2023

--

‘Near Me’ searches refer to location-based search queries often used when individuals are looking for something in their immediate vicinity. When a user performs a ‘Near Me’ search, Google utilizes the user’s current location to provide results that are in close proximity to them.

Near me searches plays a major role in ones daily life, for instance we may need immediate heath care attention or we need medicines, anything for that reason is just one click away to find them. In this article I will explain you how to implement the same using MongoDB’s Geospatial queries for the application of finding nearest hospitals or pharmacies closer to my house in Bangalore, India.

What are Geospatial Queries?

MongoDB’s Geospatial queries are designed for working with geospatial data, enabling various operations on such data. MongoDB offers a range of geospatial query operators to facilitate these tasks. You can store geospatial information in MongoDB either as GeoJSON objects or in traditional coordinate pairs. When dealing with Earth-like spherical calculations, it’s advisable to store location data as GeoJSON objects.

Structure of GeoJSON data:

<field>: { type: <GeoJSON type> , coordinates: [<longitude>, <latitude> ] }

Type — Here in the above structure type particularly is of GeoJSON Object Type which includes : Points, LineString, Polygon, MultiString and more.

Coordinates — to specify data as legacy coordinate pairs you can use an array or else an embedded document. As MongoDB community recommends using array type I will be using array over embedded document.

Example:

location: {
type: "Point",
coordinates: [77.5208475, 12.970375]
}

Implementation of “Near me” using Geospatial Queries

We will learn more precisely about creating and reading of geospatial data with the illustration below: I will describe how to apply MongoDB’s Geospatial queries to find hospitals or pharmacies near my proximity in Bangalore.

The below map shows the markings of some of the major Hospitals and Pharmacy in my vicinity. The pointers with flags are the hospitals and pharmacies, the navigator with house symbol is my place of living.

Map snippet with markings of Hospitals and Pharmacy

To start, I added approximately ten locations to the ‘places’ collection utilizing both the ‘insertOne’ and ‘insertMany’ methods.

db.locations.insertOne({ 
Name : "Manasa Hospital", location :
{ type : "Point" , coordinates : [77.5252121, 12.9688314] },
Category : "Hospital"
})

This MongoDB insertOne query is used to add a new document to the “locations” collection. The document represents a hospital with the name “Manasa Hospital,” categorized under “Hospital.” The hospital’s geographical location is specified using GeoJSON format, with coordinates (77.5252121, 12.9688314) representing its longitude and latitude respectively. This query effectively inserts this hospital’s information into the collection for future retrieval or geospatial queries related to hospitals.

Below snapshot shows how I inserted multiple documents at once using insertMany method:

Note When using insertMany, the inputs should be provided within an array. Additionally “ db.locations.find().pretty() “ is used to list down all the documents in the collection.

The $near operator

$near operator is used in a geospatial query to retrieve documents in order of proximity, starting from the closest and moving farther away.

To use $near, you need to have a geospatial index, If you’re using a GeoJSON point, you should have a 2dsphere index or else If you’re specifying a point using legacy coordinates, you should have a 2d index.

Geospatial Indexing

Geospatial indexes are designed to enable queries on data stored in either GeoJSON format or traditional coordinate pairs. They serve to enhance query performance for geospatial data and facilitate specific geospatial query types.

MongoDB offers two primary types of geospatial indexes:

2dsphere Indexes: These support queries that involve interpreting geometry on a spherical surface.

2d Indexes: These support queries that involve interpreting geometry on a flat, two-dimensional surface.

Syntax: 

db.collection.createIndex( { <location field> : "2dsphere" } )

Implementation:

db.locations.createIndex({location : "2dsphere" })

Finding the nearest location

db.locations.find({
location:{ $near:{ $geometry:
{ type: "Point",
coordinates: [77.5208475, 12.970375]}}}
})

The result consists of a list of medical centers, and they are organized in ascending order according to their distance from the queried location.

Snippet of MongoDB console that returns all the nearest health centers

Next, I will demonstrate how to perform queries for two scenarios, that is searching exclusively for hospitals and retrieving health centers located within a specified radius in kilometers.

Query to find all the nearest Pharmacies only:

db.locations.find({
$and: [{ Category: "Pharmacy" },
{location: {$near: {$geometry:
{type: "Point",coordinates:[77.5208475, 12.970375] }}}}]
})

The given query finds all pharmacies that are near a specific geographical point, and sorts them by their proximity to that point. In other words, it finds the nearest pharmacies to a given location.

Query to find all the health care centers within 3 kilometers radius:

db.locations.find({
location:{ $near:{ $geometry:
{ type: "Point", coordinates: [77.5208475, 12.970375]} ,
$maxDistance: 3000 }}
})

The $maxDistance operator is used to specify the maximum distance that a document can be from the specified point in order to be returned in the results.

To summarize, MongoDB exhibits impressive performance and precision when it comes to conducting geospatial analysis. The article effectively assists in acquiring a fundamental grasp of employing geospatial queries. In other words, the article serves as a valuable resource for gaining a foundational understanding of how to utilize geospatial queries.

Subscribe to DDIntel Here.

DDIntel captures the more notable pieces from our main site and our popular DDI Medium publication. Check us out for more insightful work from our community.

Register on AItoolverse (alpha) to get 50 DDINs

Join our network here: https://datadriveninvestor.com/collaborate

DDI Official Telegram Channel: https://t.me/+tafUp6ecEys4YjQ1

Follow us on LinkedIn, Twitter, YouTube, and Facebook.

--

--

Bachelor of Engineering in Computer | Migration Factory Associate Specialist at Informatica | Certified in IBM Data Science | Data Integration Practitioner