The MongoDB Stage Every Location-Based App Should Use


Hey devs! 👋
Want to find documents closest to a specific location in MongoDB? $geoNear is your best bet! 📍
It calculates distance and sorts results by proximity—ideal for maps, nearby searches, and geo-powered apps. Let’s dive in! 🌍
Ever wondered how apps like Uber, Zomato, or Google Maps instantly show you the closest cabs, restaurants, or stores based on your current location? Behind the scenes, they rely on geospatial queries to deliver lightning-fast and accurate results. In MongoDB, this magic happens through a powerful aggregation stage called $geoNear
.
In this article, we’ll explore the $geoNear
stage—what it is, how it works, where it shines in real-world use, and a simple pipeline example to get you started. Whether you're building a delivery app or a local directory, $geoNear
is your go-to tool for geolocation-based queries.
What is $geoNear
in MongoDB? 🔍
$geoNear
is an aggregation stage in MongoDB used to return documents sorted by proximity to a specific geographical point.
It performs:
A geospatial proximity search using a given point (
near
)Calculates distance from that point to each matched document
Optionally filters results by a maximum distance (
maxDistance
)Adds a computed field (usually
distanceField
) to show how far each document is from thenear
point
💡 Note:
$geoNear
must be the first stage in the aggregation pipeline, and the field being used for geospatial queries must be indexed with a 2dsphere index.
Real-World Scenario: Local Café Finder App 🌍
Imagine you're building a Café Finder App. A user opens the app and wants to see a list of cafés within 5 kilometers of their current location, sorted from nearest to farthest.
Here's how $geoNear
helps:
You store cafés' coordinates in MongoDB.
User shares their current location (
longitude
,latitude
).The app uses
$geoNear
to fetch nearby cafés in real-time.
Why & Where is $geoNear
Used? 🚀
Use Cases ✅
Local business directories: Show nearby shops or restaurants
Ride-sharing apps: Find the nearest drivers
Delivery services: Suggest closest delivery hubs
Social apps: Match users by proximity
Emergency response: Locate nearest hospitals, police stations, etc.
Why Use $geoNear
✅
Accurate and efficient geospatial queries
Results are automatically sorted by distance
Flexible filtering using
maxDistance
andquery
Scalable with proper indexing
Simple $geoNear
Pipeline Example 🛠️
Let’s say we have a MongoDB collection cafes
like this:
{
"name": "Brew Bliss",
"location": {
"type": "Point",
"coordinates": [77.5946, 12.9716] // [longitude, latitude]
}
}
Ensure your location
field is indexed:
db.cafes.createIndex({ location: "2dsphere" });
Aggregation pipeline using $geoNear
:
db.cafes.aggregate([
{
$geoNear: {
near: {
type: "Point",
coordinates: [77.598, 12.9718], // User's current location
},
distanceField: "dist.calculated", // Field to store distance result
maxDistance: 5000, // 5 km radius
spherical: true,
query: { openNow: true }, // Optional filter
},
},
]);
What’s Happening Here? 🧾
near
: Center point for proximity calculationdistanceField
: Stores computed distance (in meters)maxDistance
: Restricts results within a 5 km radiusspherical
: Enables accurate distance on Earth’s surfacequery
: Filters only open cafés
Best Practices 📌
Always create a 2dsphere index on the geospatial field
Keep
$geoNear
as the first stage in the pipelineUse
maxDistance
to limit result size and improve performanceUse
spherical: true
for real-world coordinates (lat/long)
Wrapping Up 📦
MongoDB’s $geoNear
stage is a powerful feature when working with geolocation data. From delivery services to dating apps, it enables a seamless way to fetch nearby items with accuracy and speed. Just remember to index properly and structure your location data using GeoJSON format.
If your app deals with location-based services, $geoNear
is your best friend in MongoDB’s aggregation pipeline!
Want to Go Deeper? 🧠
Check out MongoDB’s official docs on $geoNear or try building a real-time location feature in your next project!
Thank You!
Thank you for reading!
I hope you enjoyed this post. If you did, please share it with your network and stay tuned for more insights on software development. I'd love to connect with you on LinkedIn or have you follow my journey on HashNode for regular updates.
Happy Coding!
Darshit Anjaria
Subscribe to my newsletter
Read articles from Darshit Anjaria directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Darshit Anjaria
Darshit Anjaria
I’m a problem solver at heart, driven by the idea of building solutions that genuinely make a difference in people’s everyday lives. I’m always curious, always learning, and always looking for ways to improve the world around me through thoughtful, impactful work. Beyond building, I love giving back to the community — whether it’s by sharing what I’ve learned through blogs, tutorials, or helpful insights. My goal is simple: to make technology a little more accessible and useful for everyone. Let’s learn, build, and grow together.