What is GeoJSON in MongoDB: Explained with Examples
GeoJSON in MongoDB is a format for storing geographic data like points, lines, and polygons using JSON. It allows MongoDB to perform geospatial queries such as finding locations near a point or within an area.How It Works
GeoJSON is a way to represent geographic shapes and locations using JSON format. Think of it like drawing on a map with points (like a pin), lines (like a road), or polygons (like a park boundary). MongoDB uses GeoJSON to store these shapes inside documents.
When you save GeoJSON data in MongoDB, it understands the shape and location, so you can ask questions like "Which stores are within 5 miles?" or "Find all parks near me." This works because MongoDB has special geospatial indexes that organize the data efficiently, just like how a GPS system quickly finds places on a map.
Example
This example shows how to store a point location using GeoJSON in MongoDB and query for nearby places.
db.places.insertOne({
name: "Coffee Shop",
location: {
type: "Point",
coordinates: [-73.856077, 40.848447]
}
});
// Create a geospatial index
db.places.createIndex({ location: "2dsphere" });
// Find places near a given point
db.places.find({
location: {
$near: {
$geometry: {
type: "Point",
coordinates: [-73.856077, 40.848447]
},
$maxDistance: 5000
}
}
});When to Use
Use GeoJSON in MongoDB when you need to store and query geographic data like locations, routes, or areas. It is perfect for apps that show maps, find nearby places, or analyze spatial relationships.
For example, delivery services use GeoJSON to find drivers near customers, real estate apps show houses within a neighborhood, and travel apps highlight points of interest around you.
Key Points
- GeoJSON stores geographic data as JSON objects with types like Point, LineString, and Polygon.
- MongoDB supports GeoJSON for geospatial queries and indexing.
- Use 2dsphere indexes to enable efficient spatial queries on GeoJSON data.
- GeoJSON helps build location-based features like nearby search and area filtering.