How to use geospatial operators in MongoDB to filter data

MongoDB allows us to query and filter data in a database based on geographical coordinates using geospatial operators. These operators are used to search for data in proximity to a point or within a specific radius and more.

Different geospatial operators are used for querying and filtering data. Some of them are as follows:

  • $near: It returns geospatial objects in proximity to a point by calculating the proximity based on the distance between the coordinates. These coordinates are that of the specified point and a document's location coordinates.

  • $geoWithin: It selects documents that are within a bounding geometric shape, such as a polygon or a circle.

  • $geoIntersects: It selects documents that intersect with a specified geometric shape.

Note: You can read more about these operators here.

Here is a step-by-step process of using geospatial operators in MongoDB to filter data:

Step 1: Set up the database and collection

We'll use the MongoDB Atlas database in our example. We need to create a MongoDB cluster and get the connection string to connect our application with the cluster. Follow the steps here to do so. We also need to allow access to the 0.0.0.0/0 IP address to interact with the database. Next, we will create a new database and a collection within this database. For this example, we will name our database locations_db and the collection locations.

Let’s save the connection string, database, and collection names to use throughout this example. To do so, follow these steps:

  1. Click the “Edit” button in the following widget.

  2. Paste the values in the relevant fields.

  3. Click the “Save” button.

As soon as the value is saved, we can print the values by clicking the “Run” button.

console.log("MONGO_URI: ", process.env.MONGO_URI)
console.log("Database name: ", process.env.DATABASE_NAME)
console.log("Collection name: ", process.env.COLLECTION_NAME)

Step 2: Insert sample documents into the collection

Once we have created the locations collection, we will insert some sample documents with geospatial coordinates. Run the code below to insert sample documents into the collection:

// Connect to the MongoDB database
const { MongoClient } = require('mongodb');
const uri = `${process.env.MONGO_URI}`;
const client = new MongoClient(uri);

async function insertDocuments() {
  try {
    await client.connect();

    const database = client.db(`${process.env.DATABASE_NAME}`);
    const collection = database.collection(`${process.env.COLLECTION_NAME}`);

    // Sample documents with geospatial coordinates
    const documents = [
      {
        name: 'Seattle',
        location: { type: 'Point', coordinates: [-122.3321, 47.6062] },
      },
      {
        name: 'London',
        location: { type: 'Point', coordinates: [0.1276, 51.5072] },
      },
      // Add more sample documents as needed
    ];

    // Insert the documents
    const result = await collection.insertMany(documents);
    console.log(`${result.insertedCount} documents inserted.`);
  } catch (error) {
    console.error('Error inserting documents:', error);
  } finally {
    await client.close();
  }
}

// Call the function to insert the documents
insertDocuments();
Insert documents into the collection

Step 3: Create a geospatial index

To filter data based on geospatial queries, we need to create a geospatial index on the field containing the geospatial coordinates. In our example, it will be created on the location field. Follow the steps below to create the geospatial index:

  1. Navigate to the locations collection that was created earlier.

  2. Click the "Indexes" tab.

  3. In the "Indexes" view, click the "Create Index" button.

  4. In the "Fields" section, replace the default field name with location.

  5. Enter 2dsphere as the value to the location value.

  6. Click the "Review" followed by the "Create" button to create the geospatial index.

Click the "Indexes" tab
1 of 4

Code example

Now that we have created a geospatial index and added sample data to our database, we will use geospatial operators to filter data based on location. Let's look at an example where we will use the $near operator:

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

async function run() {
  const uri = `${process.env.MONGO_URI}`;
  const client = new MongoClient(uri);

  try {
    await client.connect();

    const database = client.db(`${process.env.DATABASE_NAME}`);
    const collection = database.collection(`${process.env.COLLECTION_NAME}`);


    // Perform a geospatial query
    const query = {
      location: {
        $near: {
          $geometry: {
            type: 'Point',
            coordinates: [-122.3223, 47.6082]
          },
          $maxDistance: 1500
        }
      }
    };

    const result = await collection.find(query).toArray();
    console.log(result);
  } finally {
    await client.close();
  }
}

run().catch(console.error);
Using the $near operator to filter data

Code explanation

  • Line 3: We define the run function which connects to the MongoDB Atlas cluster to perform a query using a geospatial operator.

  • Lines 4–5: We define the MongoDB connection URI and create a new instance of the MongoDB client.

  • Lines 8–11: We establish a connection to the MongoDB database using the connect method. We select the locations_db database and the locations collection from this database. We create the database and the collection earlier.

  • Lines 14–24: Here, we define our geospatial query. Our query searches the locations collection for documents that are near a specified coordinate point within a maximum distance of 500 meters. We use the $near geospatial operator and the $geometry and $maxDistance geometry specifiers to perform this query.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved