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

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. These queries are integral to applications involving mapping, geolocation, and spatial analysis. In a geospatial query, you 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.

Approach

To perform geospatial queries in MongoDB using Node.js, first, ensure your MongoDB collection has geospatial indexes. Define functions to find places near a point, within a polygon, and within a circle, showcasing how to use $near and $geoWithin operators for geospatial queries.

Steps to Perform Geospatial Queries in MongoDB

Step 1: Setup MongoDB

Install MongoDB

Make sure you have MongoDB installed and running on your machine. You can download and install it from the official MongoDB website.

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

Insert sample geospatial data into your collection. This data will include Point types with coordinates.

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

Create a geospatial index on the location field to enable efficient geospatial queries.

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

Step 4: Setup Node.js Project

Initialize Node.js Project

Create a new directory for your project and initialize it.

npm init -y

Install MongoDB Driver

Install the MongoDB Node.js driver.

npm install mongodb

Step 5: Write the Node.js Code

Create a file named app.js and write the code to connect to MongoDB and perform geospatial queries.

JavaScript
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);

Step 6: Run the Code

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

node app.js

Output: You should see the results of the geospatial queries printed in the console.

output

Conclusion

We explored how to perform geospatial queries in MongoDB using Node.js. We covered setting up the database, creating geospatial indexes, and performing various types of geospatial queries.




Reffered: https://www.geeksforgeeks.org


MongoDB

Related
How to Store Images in MongoDB using NodeJS? How to Store Images in MongoDB using NodeJS?
How to Perform Aggregation Operations in MongoDB using Node.js? How to Perform Aggregation Operations in MongoDB using Node.js?
How to use MongoDB Projection in Mongoose? How to use MongoDB Projection in Mongoose?
How to Insert a Document into a MongoDB Collection using Node.js? How to Insert a Document into a MongoDB Collection using Node.js?
How To Perform a Find Operation With Sorting In MongoDB Using Node.js? How To Perform a Find Operation With Sorting In MongoDB Using Node.js?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
19