Geospatial Data in MongoDB: Storage, Indexing, and Queries

Photo by Thomas Kinto on Unsplash

Geospatial data plays a crucial role in various types of applications. MongoDB offers a comprehensive set of features to handle geospatial data efficiently. In this article, we’ll explore how to store geospatial data, create geospatial indexes, and run geospatial queries in MongoDB.

Storing Geospatial Data

Where to Store

You can store geospatial data alongside other data in your MongoDB documents. This makes it easy to associate geographic coordinates with other attributes of an object.

GeoJSON Format

Geospatial data in MongoDB must adhere to the GeoJSON format. MongoDB supports various GeoJSON types like Point, LineString, and Polygon.

Coordinate Order

In MongoDB, coordinates are stored as [longitude, latitude], contrary to the more commonly used [latitude, longitude] order.

Example Document

{
name: "Central Park",
location: {
type: "Point",
coordinates: [-73.9712, 40.7831] // [longitude, latitude]
}
}

Geospatial Indexes

2dsphere Index

To perform geospatial queries efficiently, you can add a 2dsphere index on the field containing the GeoJSON data.

Creating a 2dsphere Index

db.collection('places').createIndex({ location: "2dsphere" });

Geospatial Queries

MongoDB provides several operators to facilitate geospatial queries:

$near

Finds documents nearest to a given point.

db.collection('places').find({
location: {
$near: {
$geometry: {
type: "Point",
coordinates: [-73.9654, 40.7829] // Central Park South
}
}
}
});

$geoWithin

Finds documents within a given geometric shape.

db.collection('places').find({
location: {
$geoWithin: {
$geometry: {
type: "Polygon",
coordinates: [
// array of points making up the boundary
]
}
}
}
});

$geoIntersects

Finds documents that intersect with a given geometric shape.

db.collection('places').find({
location: {
$geoIntersects: {
$geometry: {
type: "LineString",
coordinates: [
// array of points making up the line
]
}
}
}
});

Summary

Geospatial data in MongoDB offers a robust set of features for applications requiring location-based functionalities. By understanding how to store this data in the GeoJSON format, create 2dsphere indexes, and use geospatial query operators like $near, $geoWithin, and $geoIntersects, you can build efficient and feature-rich geospatial applications.

,