Guides
Last updated
November 6, 2025

The Complete Guide to MongoDB Geolocation: From Storing Data to Advanced Geospatial Queries

Nicolas Rios

Table of Contents:

Get your free
IP Geolocation
 API key now
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Building Location-Aware Applications

From powering "find nearby" features in delivery apps 🚴‍♂️ to analyzing geographic trends in user behavior 📊, geospatial queries are at the heart of modern applications. But when your database has millions of locations, how do you efficiently find, say, the 50 closest stores to a user?

Storing simple latitude and longitude coordinates is straightforward, but performing fast, complex spatial queries at scale is a real engineering challenge. Naive implementations can lead to sluggish performance and unscalable architectures.

Building Location-Aware Applications - Abstr

The solution? MongoDB. With its robust, native geospatial capabilities, MongoDB enables developers to model, index, and query location data efficiently. This guide will walk you through everything from the foundations of GeoJSON to building a fully functional "Nearby Locations" API endpoint.

Enter an IP address to start
Need inspiration? Try
73.162.0.1
VALIDATE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Checking
5
Results for
ip address
Country:
TEST
Region:
TEST
City:
TEST
Coordinates:
TEST
Zip code:
TEST
Connection:
TEST
Get free credits, more data, and faster results

🧱 The Foundation – Modeling Geospatial Data with GeoJSON

GeoJSON: The Lingua Franca of Location Data

MongoDB uses GeoJSON, a standardized format for representing geospatial data. Understanding its core objects is crucial for building location-aware apps:

  • Point: Represents a single coordinate, e.g., a user's location or a store.
  • LineString: Defines a path or route.
  • Polygon: Encapsulates a bounded area, such as a delivery zone or city boundary.

Best Practice: Structuring Your Documents

{

  "name": "Cafe Central",

  "cuisine": "Italian",

  "location": {

    "type": "Point",

    "coordinates": [-73.935242, 40.730610] 

  }

}

⚠️ Pro Tip: Always use [longitude, latitude] order. Swapping these values is a common pitfall that leads to unexpected query results.

⚡ The Engine – Supercharging Queries with Geospatial Indexes

Why You Can't Skip the Index

Without a geospatial index, MongoDB must perform a collection scan, checking every document for each query. This approach is slow and impractical when dealing with large datasets.

Introducing the 2dsphere Index

The 2dsphere index is MongoDB’s core geospatial index, enabling Earth-like calculations. It’s essential for nearly all location-aware applications.

Creating a 2dsphere Index

Here’s how to create it on the location field:

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

  • This simple step dramatically improves query performance, allowing MongoDB to handle millions of location points efficiently.

🧰 The Toolkit – A Deep Dive into Geospatial Query Operators

MongoDB offers powerful operators for different geospatial needs:

1. Proximity Queries with $near & $nearSphere

Use Case: Find the 20 closest restaurants to a user's current location.

The $near operator sorts results automatically by distance and supports $minDistance and $maxDistance to refine searches.

db.restaurants.find({

  location: {

    $near: {

      $geometry: { type: "Point", coordinates: [-73.935242, 40.730610] },

      $maxDistance: 5000  // meters

    }

  }

})

2. Inclusion Queries with $geoWithin

Use Case: Identify all delivery drivers within a specific neighborhood.

$geoWithin selects documents completely inside a defined GeoJSON shape, such as a polygon representing a city block.

db.drivers.find({

  location: {

    $geoWithin: {

      $geometry: {

        type: "Polygon",

        coordinates: [[

          [-73.935,40.730],

          [-73.935,40.740],

          [-73.925,40.740],

          [-73.925,40.730],

          [-73.935,40.730]

        ]]

      }

    }

  }

})

3. Intersection Queries with $geoIntersects

Use Case: A user draws a route on a map, and you want to find points of interest along the path.

$geoIntersects returns documents whose geospatial data overlaps with a GeoJSON shape.

db.pointsOfInterest.find({

  location: {

    $geoIntersects: {

      $geometry: {

        type: "LineString",

        coordinates: [

          [-73.935,40.730],

          [-73.925,40.740]

        ]

      }

    }

  }

})

Practical Walkthrough – Building a "Nearby Locations" API Endpoint

Let’s bring it all together with a hands-on example.

Step 1: Getting the User's Location

First, acquire the user's coordinates. On mobile, this is typically via GPS; on the backend, it can be derived from an IP address.

Step 2: Setting Up the Database and Collection

Create a MongoDB cluster using Atlas, connect via Compass, and insert sample restaurants data:

db.restaurants.insertMany([

  { name: "Cafe Central", location: { type: "Point", coordinates: [-73.935242, 40.730610] } },

  { name: "Bistro Bella", location: { type: "Point", coordinates: [-73.925242, 40.735610] } }

])

Step 3: Creating the 2dsphere Index

Run the createIndex command from Section 2 to ensure efficient queries.

Step 4: Writing the API Query (Node.js/Express Example)

Here’s a simple Express.js endpoint that returns nearby restaurants:

const express = require('express');

const { MongoClient } = require('mongodb');

const app = express();

const port = 3000;

const uri = 'your_mongodb_connection_string';

const client = new MongoClient(uri);

app.get('/nearby', async (req, res) => {

  const { lat, lon } = req.query;

  await client.connect();

  const collection = client.db('geoDB').collection('restaurants');

  const nearby = await collection.find({

    location: {

      $near: {

        $geometry: { type: "Point", coordinates: [parseFloat(lon), parseFloat(lat)] },

        $maxDistance: 5000

      }

    }

  }).toArray();

  res.json(nearby);

});

app.listen(port, () => console.log(`Server running on port ${port}`));

This endpoint is ready to power location-aware features in any modern application.

Conclusion: Go Build Something Location-Aware 🚀

Key Takeaways

MongoDB transforms complex spatial operations into simple, high-performance queries, making it an ideal choice for developers building location-based features.

Final CTA: To fuel your geospatial features with precise, real-time location data, get started with a free API key from AbstractAPI's IP Geolocation API today! 🌍

🔧 Practical Example – Build a Nearby Locations API (Node.js)

Let’s build a production-ready API that returns nearby restaurants.

✅ Example Express.js endpoint

app.get('/nearby', async (req, res) => {

  const { lat, lon } = req.query;

  const results = await db.collection('locations').find({

    location: {

      $near: {

        $geometry: { type: "Point", coordinates: [parseFloat(lon), parseFloat(lat)] },

        $maxDistance: 10000

      }

    }

  }).limit(20).toArray();

  res.json(results);

});

🔥 And guess what? You can detect a user’s location easily using their IP address 👇

🌍 Get User Location Automatically (IP Geolocation)

Instead of forcing users to enable GPS, you can get location from IP using the 💪

➡️ AbstractAPI IP Geolocation API

Try it: https://ipgeolocation.abstractapi.com/v1/?api_key=YOUR_KEY 

You’ll get: 

{

  "latitude": 40.7128,

  "longitude": -74.0060,

  "city": "New York"

}

Use those coordinates in your MongoDB geospatial queries ✅

✅ Conclusion — Build Smarter, Location-Aware Apps

You just learned:

✅ How to store location data in MongoDB using GeoJSON

✅ Why the 2dsphere index is required

✅ How to use $near, $geoWithin, and $geoIntersects

✅ How to build a real nearby search API

✅ How to get user location using IP with AbstractAPI 🌍

MongoDB makes geospatial search efficient and production-ready. Paired with AbstractAPI IP Geolocation, you can create truly location-aware applications.

🔗 Helpful AbstractAPI resources

How IP Geolocation Works

What Is API Rate Limiting?

REST API Best Practices

❓ MongoDB Geolocation FAQs 

What is MongoDB Geolocation?

  • MongoDB geolocation allows storing and querying geographic data like coordinates, routes, and areas using GeoJSON and geospatial indexes.

What is a 2dsphere index?

  • A MongoDB index that enables accurate geospatial calculations on Earth-like spheres.

How do I find nearby locations in MongoDB?

  • Use a $near geospatial query with a 2dsphere index.

How do I filter within a radius?

  • Use $near with $maxDistance in meters.

Can MongoDB detect user location?

  • Yes — use an IP Geolocation API like AbstractAPI to get coordinates from IP, then query MongoDB.
Nicolas Rios

Head of Product at Abstract API

Get your free
IP Geolocation
key now
See why the best developers build on Abstract
get started for free

Related Articles

Get your free
IP Geolocation
key now
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required