Open In App

How to Perform Geospatial Queries in MongoDB using Node.js?

Last Updated : 20 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A geospatial query involves searching for data based on geographic locations. It allows developers to identify and analyze data associated with specific coordinates or within a defined proximity of a given point. In a geospatial query, we can define a geographic shape, such as a point, line, or polygon, and search for data that intersects, contains, or lies within a certain distance of that shape.

This capability enables the retrieval of data relevant to specific areas on the Earth's surface. In this article, we'll explain the process of performing geospatial queries using MongoDB and Node.js. We’ll cover the steps required to set up your database, insert geospatial data, create geospatial indexes, and run queries based on coordinates.

What Are Geospatial Queries?

A geospatial query in MongoDB enables us to search and analyze data based on its geographic location. We can define a geographic shape (such as a point, line, or polygon) and query for documents that intersect, contain, or lie within a specific area. These queries are essential for apps that need to filter and display data based on proximity or geographic boundaries.

Some common types of geospatial queries include:

  • Nearby queries: Find places within a certain radius of a given point.
  • Polygon queries: Search for points within a defined polygon.
  • Circle queries: Find data within a specified circular area.

MongoDB supports these queries using special indexes and operators, which makes them efficient and easy to implemen

Steps to Perform Geospatial Queries in MongoDB using Node.js

Geospatial queries in MongoDB allow us to efficiently search and analyze data based on geographic locations. With the integration of Node.js and MongoDB, we can perform location-based queries, such as finding nearby places or searching within specific geographic boundaries. Below, we’ll walk through the key steps to set up MongoDB, insert geospatial data, create indexes, and execute geospatial queries using Node.js.

Step 1: Setup MongoDB

Before we can perform geospatial queries, make sure MongoDB is installed and running on your local machine.

  • Install MongoDB: We can download MongoDB from the official MongoDB website and follow the installation instructions for our operating system.
  • Create Database and Collection: Open your MongoDB shell or use a GUI tool like MongoDB Compass to create a database and collection.
mongo
use geospatial
db.createCollection("places")

Step 2: Insert Sample Geospatial Data

Now that we have our MongoDB database and collection set up, Insert sample geospatial data into our collection. This data will include Point types with coordinates. This sample data includes three places with coordinates representing geographic points.

db.places.insertMany([
{ name: "Place 1", location: { type: "Point", coordinates: [ -73.97, 40.77 ] } },
{ name: "Place 2", location: { type: "Point", coordinates: [ -73.88, 40.78 ] } },
{ name: "Place 3", location: { type: "Point", coordinates: [ -73.95, 40.79 ] } }
])

Step 3: Create Geospatial Index

To make geospatial queries efficient, MongoDB requires a geospatial index. Specifically, we will create a 2dsphere index on the location field of the places collection.

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

The 2dsphere index is used for queries involving spherical geometry, such as calculating distances or finding nearby points.

Step 4: Setup Node.js Project

Now that your MongoDB setup is complete, let’s move on to integrating MongoDB with Node.js.

1. Initialize Node.js Project

First create a new directory for your Node.js project and initialize it.

mkdir geospatial-app
cd geospatial-app
npm init -y

2. Install MongoDB Driver

We will need the MongoDB driver for Node.js. Install it using npm:

npm install mongodb

Step 5: Write Node.js Code for Geospatial Queries

Create a new file called app.js. This file will contain the Node.js code to connect to MongoDB and perform geospatial queries.

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

const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);

async function run() {
try {
await client.connect();
console.log('Connected to MongoDB');
const database = client.db('geospatial');
const collection = database.collection('places');

// Function to find places near a point
async function findPlacesNearPoint() {
const point = { type: "Point", coordinates: [ -73.96, 40.78 ] };
const maxDistance = 2000; // meters

const places = await collection.find({
location: {
$near: {
$geometry: point,
$maxDistance: maxDistance
}
}
}).toArray();

console.log('Places near the point:', places);
}

// Function to find places within a polygon
async function findPlacesWithinPolygon() {
const polygon = {
type: "Polygon",
coordinates: [[
[ -73.97, 40.77 ],
[ -73.88, 40.77 ],
[ -73.88, 40.80 ],
[ -73.97, 40.80 ],
[ -73.97, 40.77 ]
]]
};

const places = await collection.find({
location: {
$geoWithin: {
$geometry: polygon
}
}
}).toArray();

console.log('Places within the polygon:', places);
}

// Function to find places within a circle
async function findPlacesWithinCircle() {
const center = [ -73.96, 40.78 ];
const radius = 2000 / 6378137; // radius in radians (Earth radius in meters)

const places = await collection.find({
location: {
$geoWithin: {
$centerSphere: [ center, radius ]
}
}
}).toArray();

console.log('Places within the circle:', places);
}

await findPlacesNearPoint();
await findPlacesWithinPolygon();
await findPlacesWithinCircle();

} finally {
await client.close();
}
}

run().catch(console.dir);

Explanation: This code performs a geospatial query using the $near operator, which finds documents near a specified point within a maximum distance. The coordinates [ -73.97, 40.77 ] represent a location in New York City, and the query finds places within a 5km radius.

Step 6: Run the Code

Execute your Node.js script to see the results of the geospatial queries.

node app.js

Output:

output

Explanation: If successful, we should see a list of places that are located within 5km of the specified point.

Conclusion

Geospatial queries in MongoDB allows us to perform location-based searches, which are vital for applications involving mapping, geolocation, and spatial analysis. By integrating MongoDB with Node.js, we can efficiently store, query, and analyze geographic data. In this guide, we covered everything from setting up MongoDB to performing specific geospatial queries using the 2dsphere index and $near operator. Make sure to take advantage of MongoDB’s efficient indexing and querying capabilities to build location-based services and geospatial analysis tools.


Next Article

Similar Reads