Geospatial Queries with Python MongoDB
Last Updated :
20 Feb, 2025
Geospatial data plays a crucial role in location-based applications such as mapping, navigation, logistics, and geographic data analysis. MongoDB provides robust support for geospatial queries using GeoJSON format and 2dsphere indexes, making it an excellent choice for handling location-based data efficiently.
In this article, we will cover the various ways of using geospatial in MongoDB and explain the GeoJSON polygon and point types

What is GeoJSON Format in MongoDB?
GeoJSON is an open-source format based on JSON (JavaScript Object Notation) that represents geographic features such as points, lines, and polygons. MongoDB supports GeoJSON objects to store and manipulate geospatial data efficiently. GeoJSON is an open-source format that describes simple geographical features. It includes two essential fields:
- type: Specifies the GeoJSON object type (e.g., Point, Polygon, MultiPolygon).
- coordinates: Contains the object’s coordinates. When specifying latitude and longitude, list the longitude first and then the latitude.
Note: If specifying latitude and longitude coordinates, list the longitude first and then latitude.
Example of GeoJSON Object (Point Representation):
{
"type": "Point",
"coordinates": [-73.856077, 40.848447]
}
Explanation: Here, -73.856077 is the longitude, and 40.848447 is the latitude.
Supported GeoJSON Types in MongoDB:
- Point:
{ "type": "Point", "coordinates": [longitude, latitude] }
- LineString:
{ "type": "LineString", "coordinates": [[lng1, lat1], [lng2, lat2]] }
- Polygon:
{ "type": "Polygon", "coordinates": [[[lng1, lat1], [lng2, lat2], [lng3, lat3], [lng1, lat1]]] }
- MultiPolygon: A collection of multiple polygons.
Setting Up MongoDB for Geospatial Queries
MongoDB provides two indexing types to work with geospatial data:
2d Index
(Legacy Coordinate Pairs) – Used for flat coordinate spaces.2dsphere Index
– Used for real-world spherical calculations (Recommended).
Step 1: Create a MongoDB Collection and Insert GeoJSON Data
import pymongo
# Connect to MongoDB
client = pymongo.MongoClient("your_connection_string")
# Select database
db = client["geospatial_db"]
# Select collection
locations = db["places"]
# Insert a GeoJSON document (Example: A cafe location)
location_data = {
"name": "Central Cafe",
"location": {
"type": "Point",
"coordinates": [-74.006, 40.7128] # Longitude, Latitude
}
}
# Insert document
locations.insert_one(location_data)
Step 2: Create a 2dsphere
Index for Efficient Queries
Indexes improve query performance by enabling geospatial computations. Before running geospatial queries, create an index on the location
field:
locations.create_index([("location", pymongo.GEOSPHERE)])
Using Geospatial Queries in MongoDB with Python
MongoDB supports several types of geospatial queries:
1. Find Nearby Locations ($near
)
Find locations within a certain radius (e.g., within 5 km of a given point). Use $maxDistance
(in meters) to filter nearby results.
query = {
"location": {
"$near": {
"$geometry": {
"type": "Point",
"coordinates": [-74.006, 40.7128] # Search around this location
},
"$maxDistance": 5000 # Distance in meters (5 km)
}
}
}
nearby_places = locations.find(query)
for place in nearby_places:
print(place)
2. Find Points Within a Specific Area ($geoWithin
)
Find locations inside a defined polygon (e.g., a city boundary):
polygon_query = {
"location": {
"$geoWithin": {
"$geometry": {
"type": "Polygon",
"coordinates": [[
[-74.0, 40.7], [-74.02, 40.72], [-74.04, 40.7], [-74.0, 40.7]
]]
}
}
}
}
inside_places = locations.find(polygon_query)
for place in inside_places:
print(place)
Visualizing Geospatial Data in Python
To analyze and visualize geospatial data stored in MongoDB, we use Matplotlib for plotting and Basemap for mapping geographic locations.
1. Install Required Libraries
To work with geospatial data in Python, install the following modules:
pymongo (MongoDB Client for Python)
This module is used to interact with the MongoDB. To install it type the below command in the terminal.
pip install pymongo
OR
conda install pymongo
Matplotlib (Graph Plotting Library)
This library is used for plotting graphs
pip install matplotlib
Basemap (Map Visualization in Python)
This module is used for plotting maps using Python. To install this module type the below command in the terminal.
conda install basemap
2. Setting Up MongoDB Atlas
To use MongoDB Atlas for storing geospatial data, follow these steps:
- Open the MongoDB Atlas Cloud from here.
- Create the account by choosing the package suitable for you (You may also choose the free version which will be enough for this article and for learning purpose).
- Click on the Cluster view positioned at the left menu bar.
- Click on the Ellipses button
(...)
and select Load Sample Dataset. - After the sample dataset is added then click on the connect button.

- Then whitelist the IP address (choose your current IP address or type the 0.0.0.0/0 IP for allowing it to access from everywhere. Click the button shown in the below image.

- Click Connect to Applications and copy the connection URI.
- Store this connection URI in a variable (e.g.,
course_cluster_uri
).
3. Implementation: Fetching and Visualizing Geospatial Data
Below is a Python script to connect to MongoDB Atlas, retrieve geospatial data, and plot it on a map.
a) Connecting to MongoDB
import pymongo
import pprint
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
course_cluster_uri = 'your_connection_string'
course_client = pymongo.MongoClient(course_cluster_uri)
# sample Database
db = course_client['sample_geospatial']
# sample Collection
shipwrecks = db['shipwrecks']
b) Fetching Geospatial Data
l = list(shipwrecks.find({}))
lngs = [x['londec'] for x in l]
lats = [x['latdec'] for x in l]
c) Plotting Data on a Map
# Clear the figure (this is nice if you
# execute the cell multiple times)
plt.clf()
# Set the size of our figure
plt.figure(figsize =(14, 8))
# Set the center of our map with our
# first pair of coordinates and set
# the projection
m = Basemap(lat_0 = lats[0],
lon_0 = lngs[0],
projection ='cyl')
# Draw the coastlines and the states
m.drawcoastlines()
m.drawstates()
# Convert our coordinates to the system
# that the projection uses
x, y = m(lngs, lats)
# Plot our converted coordinates
plt.scatter(x, y)
# Display our beautiful map
plt.show()
Output:
shipwrecks plotExplanation:
- The script connects to MongoDB Atlas and retrieves a collection of shipwreck locations stored in a geospatial dataset. It then extracts the longitude and latitude coordinates from the dataset to prepare the data for visualization.
- Using Basemap, the script plots these locations on a world map, displaying coastlines and state boundaries to provide geographical context. Finally, the shipwreck locations are visualized as red dots on the map, allowing for a clear representation of their distribution across different regions.
Conclusion
MongoDB’s geospatial queries provide a powerful way to store, index, and analyze location-based data using GeoJSON and 2dsphere indexes. By using queries like $near
and $geoWithin
, developers can efficiently search for nearby locations or points within a defined area. Combining MongoDB with Python’s pymongo library, along with visualization tools like Matplotlib and Basemap, makes it easier to work with geospatial data in real-world applications. Whether it's for navigation, logistics, ride-sharing, or mapping services, MongoDB offers a scalable and efficient solution for handling geospatial information
Similar Reads
Python MongoDB Tutorial MongoDB is a popular NoSQL database designed to store and manage data flexibly and at scale. Unlike traditional relational databases that use tables and rows, MongoDB stores data as JSON-like documents using a format called BSON (Binary JSON). This document-oriented model makes it easy to handle com
2 min read
Python MongoDB - Introduction
Python MongoDB - Getting Started
Python MongoDB - Basic
Python MongoDB - Method
Python MongoDB Queries
Python MongoDB - QueryMongoDB queries let you filter documents(records) using conditions. The find() method retrieves documents from a collection, and you can pass an optional query to specify which documents to return.A query is pass as a parameter to filter the results. This query uses key-value pairs and various opera
2 min read
Insert and Update Data - Python MongoDBIn MongoDB, insertion refers to adding new documents into a collection, while updating allows modifying existing documents. These operations are essential for managing dynamic datasets. With PyMongo library in Python, users can perform these tasks efficiently by establishing a connection to the data
3 min read
Python MongoDB - insert_one QueryMongoDB is a cross-platform document-oriented and a non relational (i.e NoSQL) database program. It is an open-source document database, that stores the data in the form of key-value pairs. MongoDB is developed by MongoDB Inc. and was initially released on 11 February 2009. It is written in C++, Go,
3 min read
Python MongoDB - insert_many QueryIn MongoDB, insert_many() method is used to insert multiple documents into a collection at once. When working with Python, this operation is performed using the PyMongo library. Instead of inserting documents one by one with insert_one(), insert_many() allows developers to pass a list of dictionarie
2 min read
Difference Between insert(), insertOne(), and insertMany() in PymongoIn PyMongo, inserting documents into a MongoDB collection can be done using different methods. Earlier versions used the insert() method, but it is now deprecated. The recommended and modern approach is to use:insert_one(): to insert a single documentinsert_many(): to insert multiple documentsThese
3 min read
Python MongoDB - Update_one()MongoDB is a cross-platform document-oriented and a non relational (i.e NoSQL) database program. It is an open-source document database, that stores the data in the form of key-value pairs.First create a database on which we perform the update_one() operation:Â Â Python3 # importing Mongoclient from
4 min read
Python MongoDB - Update_many QueryIn PyMongo, the update_many() method is used to update multiple documents in a collection that match a given filter condition. Itâs a powerful method when you need to make bulk updates to documents based on a shared field value or pattern.Syntaxcollection.update_many(filter,update,upsert=False,array
2 min read
MongoDB Python - Insert and Replace OperationsIn PyMongo, document insertion and replacement are performed using insert_one(), insert_many() and replace_one(). These methods allow you to add new documents or completely replace existing ones based on a matching filter.Syntaxcollection.insert_one(document)collection.insert_many([document1, docume
2 min read
MongoDB python | Delete Data and Drop CollectionPrerequisite : MongoDB Basics, Insert and Update Aim : To delete entries/documents of a collection in a database. Assume name of collection 'my_collection'. Method used : delete_one() or delete_many() Remove All Documents That Match a Condition : The following operation removes all documents that ma
2 min read
Python Mongodb - Delete_one()Mongodb is a very popular cross-platform document-oriented, NoSQL(stands for "not only SQL") database program, written in C++. It stores data in JSON format(as key-value pairs), which makes it easy to use. MongoDB can run over multiple servers, balancing the load to keep the system up and run in cas
2 min read
Python Mongodb - Delete_many()MongoDB is a general-purpose, document-based, distributed database built for modern application developers and the cloud. It is a document database, which means it stores data in JSON-like documents. This is an efficient way to think about data and is more expressive and powerful than the traditiona
2 min read
Python MongoDB - FindMongoDB is a cross-platform document-oriented database program and the most popular NoSQL database program. The term NoSQL means non-relational. MongoDB stores the data in the form of key-value pairs. It is an Open Source, Document Database which provides high performance and scalability along with
3 min read
Python MongoDB - find_one QueryIn PyMongo, the find_one() method is used to retrieve a single document from a MongoDB collection that matches the given filter. If multiple documents match, only the first match (based on insertion order) is returned.Syntaxcollection.find_one(filter, projection=None)Parameters:filter: (dict) Criter
2 min read
Python MongoDB - find_one_and_update QueryThe function find_one_and_update() actually finds and updates a MongoDB document. Though default-wise this function returns the document in its original form and to return the updated document return_document has to be implemented in the code. Syntax:Â coll.find_one_and_update(filter, update, option
2 min read
Python MongoDB - find_one_and_delete queryfind_one_and_delete() method in PyMongo is used to find a single document, delete it and return the deleted document. Itâs useful when you need to both remove and retrieve a document in one operation. A filter is provided to match the document and optionally a sort condition to decide which document
2 min read
Python MongoDB - find_one_and_replace Queryfind_one_and_replace() method search one document if finds then replaces with the given second parameter in MongoDb. find_one_and_replace() method is differ from find_one_and_update() with the help of filter it replace the document rather than update the existing document. Syntax:Â find_one_and_repl
2 min read
Python MongoDB - SortMongoDB is a cross-platform document-oriented database program and the most popular NoSQL database program. The term NoSQL means non-relational. MongoDB stores the data in the form of key-value pairs. It is an Open Source, Document Database which provides high performance and scalability along with
2 min read
Python MongoDB - distinct()MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. It stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational. Refer to MongoDB and Python for an in-depth introduction to the topic. N
3 min read
Python MongoDB - bulk_write()MongoDB is an open-source document-oriented database. MongoDB stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational. Refer to MongoDB: An Introduction for a much more detailed introduction on MongoDB. Now let's understand the Bulk Write opera
3 min read
Python MongoDB - $group (aggregation)In PyMongo, the aggregate() method processes data through a pipeline of stages to produce aggregated results. One key stage is $group, which groups documents based on a specified identifier like a field name and applies accumulator operations e.g., $sum, $avg, $max. It then outputs a new set of docu
2 min read
Python MongoDB - Limit QueryMongoDB is one of the most used databases with its document stored as collections. These documents can be compared to JSON objects. PyMongo is the Python driver for mongoDB. Limit() Method: The function limit() does what its name suggests- limiting the number of documents that will be returned. Ther
2 min read
Nested Queries in PyMongoMongoDB is a NoSQL document-oriented database. It does not give much importance for relations or can also be said as it is schema-free. PyMongo is a Python module that can be used to interact between the mongo database and Python applications. The data that is exchanged between the Python applicatio
3 min read
Working with Collections and documents in MongoDB
How to access a collection in MongoDB using Python?MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. MongoDB offers high speed, high availability, and high scalability. Accessing a Collection 1) Getting a list of collection: For getting a list of a MongoDB database's collections list_coll
2 min read
Get the Names of all Collections using PyMongoPyMongo is the module used for establishing a connection to the MongoDB using Python and perform all the operations like insertion, deletion, updating, etc. PyMongo is the recommended way to work with MongoDB and Python. Note: For detailed information about Python and MongoDB visit MongoDB and Pyth
2 min read
Drop Collection if already exists in MongoDB using PythonUsing drop() method we can drop collection if collection exists. If collection is not found then it returns False otherwise it returns True if collection is dropped. Syntax: drop() Example 1: The sample database is as follows:  Python3 import pymongo client = pymongo.MongoClient("mongodb://local
1 min read
How to update data in a Collection using Python?MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. MongoDB offers high speed, high availability, and high scalability. Updating Data in MongoDB We can update data in a collection using update_one() method and update_many() method.  update
2 min read
Get all the Documents of the Collection using PyMongoTo get all the Documents of the Collection use find() method. The find() method takes a query object as a parameter if we want to find all documents then pass none in the find() method. To include the field in the result the value of the parameter passed should be 1, if the value is 0 then it will b
1 min read
Count the number of Documents in MongoDB using PythonMongoDB is a document-oriented NoSQL database that is a non-relational DB. MongoDB is a schema-free database that is based on Binary JSON format. It is organized with a group of documents (rows in RDBMS) called collection (table in RDBMS). The collections in MongoDB are schema-less. PyMongo is one o
2 min read
Update all Documents in a Collection using PyMongoMongoDB is an open-source document-oriented database. MongoDB stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational. PyMongo contains tools which are used to interact with the MongoDB database. Now let's see how to update all the documents in
3 min read
Aggregation in MongoDB using PythonMongoDB is free, open-source,cross-platform and document-oriented database management system(dbms). It is a NoSQL type of database. It store the data in BSON format on hard disk. BSON is binary form for representing simple data structure, associative array and various data types in MongoDB. NoSQL is
2 min read
Indexing in MongoDB
Indexing in MongoDB using PythonBy creating indexes in a MongoDB collection, query performance is enhanced because they store the information in such a manner that traversing it becomes easier and more efficient. There is no need for a full scan as MongoDB can search the query through indexes. Thus it restricts the number of docum
2 min read
Python MongoDB - create_index QueryMongoDB is an open-source document-oriented database. MongoDB stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational. Indexing Indexing helps in querying the documents efficiently. It stores the value of a specific field or set of fields whic
2 min read
How to create index for MongoDB Collection using Python?Prerequisites: MongoDB Python Basics This article focus on the create_index() method of PyMongo library. Indexes makes it efficient to perform query requests as it stores the data in a way that makes it quick & easy to traverse. Let's begin with the create_index() method: Importing PyMongo Modul
2 min read
Get all the information of a Collection's indexes using PyMongoPrerequisites: MongoDB Python Basics This article is about displaying the information of Collection's indexes using the index_information() function of the PyMongo module. index_information() returns a dictionary where the keys are index names (as returned by create_index()) and the values are dicti
2 min read
Python MongoDB - drop_index QueryThe drop_index() library function in PyMongo is used to drop the index from a collection in the database, as the name suggests. In this article, we are going to discuss how to remove an index from a collection using our python application with PyMongo. Syntax:Â drop_index(index_or_name, session=None
3 min read
How to Drop all the indexes in a Collection using PyMongo?In PyMongo, the drop_indexes() method is used to remove all non-default indexes from a collection. It helps developers clean up or reset indexing strategies, especially during optimization or testing. The method retains the default _id index, which cannot be dropped.Syntaxcollection.drop_indexes()No
2 min read
How to rebuild all the indexes of a collection using PyMongo?According to MongoDB documentation, normally, MongoDB compacts indexes during routine updates. For most users, the reIndex command is unnecessary. However, it may be worth running if the collection size has changed significantly or if the indexes are consuming a disproportionate amount of disk space
2 min read
Conversion between MongoDB data and Structured data
Python MongoDB-Exercise
How to check if the PyMongo Cursor is Empty?MongoDB is an open source NOSQL database, and is implemented in C++. It is a document oriented database implementation that stores data in structures called Collections (group of MongoDB documents). PyMongo is a famous open source library that is used for embedded MongoDB queries. PyMongo is widely
2 min read
How to fetch data from MongoDB using Python?MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. MongoDB offers high speed, high availability, and high scalability. Fetching data from MongoDB Pymongo provides various methods for fetching the data from mongodb. Let's see them one by on
2 min read
Geospatial Queries with Python MongoDBGeospatial data plays a crucial role in location-based applications such as mapping, navigation, logistics, and geographic data analysis. MongoDB provides robust support for geospatial queries using GeoJSON format and 2dsphere indexes, making it an excellent choice for handling location-based data e
6 min read
3D Plotting sample Data from MongoDB Atlas Using PythonMongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
3 min read