MongoDB is a NoSQL database that allows you to store, index, update, and query data. It's a great, lightweight alternative to SQL databases like MySQL and PostgreSQL. MongoDB can be used to store location data and allows you to do complex geolocation searches and geospatial queries.

mongodb logo

MongoDB Atlas and MongoDB Compass

MongoDB also provides a couple of handy tools for easily getting started and working with MongoDB geospatial data. Those tools are MongoDB Compass and MongoDB Atlas.

In this tutorial, we'll use MongoDB Atlas to host a cloud-based MongoDB database that will store a sample set of geospatial data in GeoJSON format. We'll use MongoDB Compass to easily interact with this data, create index supports and do geospatial queries against the data.

Get Started With MongoDB Atlas

MongoDB Atlas is a cloud-based hosting platform that lets you host MongoDB instances without having to download or install data locally. The Atlas free tier provides a small dev environment to host your development data. Free clusters never expire, and they provide access to a robust subset of Atlas features.

Set Up Atlas

To get started with the free tier, navigate to the MongoDB Atlas homepage and click "Try Free." You'll need to provide a work email address to sign up for a free account.

MongoDB Atlas Homepage

Once you have an account and have landed on your dashboard, click "Build a Database" to create a new MongoDB database. Select the "Shared" option to get on the free plan. You can leave all the defaults for cloud providers and regions, as MongoDB will detect the best options for you. Click "Create Cluster."

Create a username and password for the database. Under that, where it says "Where would you like to connect from?" select "Local environment" and add your device's IP address to the whitelist (you can click "Add My Current IP Address" to make this easy.)

Hit "Finish and Close" and then hit "Go to Database."

Don't reinvent the wheel.
Abstract's APIs are production-ready now.

Abstract's suite of API's are built to save you time. You don't need to be an expert in email validation, IP geolocation, etc. Just focus on writing code that's actually valuable for your app or business, and we'll handle the rest.

Get started for free

Load Sample Data

In order to work with geospatial data, we'll need to import a geospatial data dataset. MongoDB provides a complete sample dataset with many collections, including a geospatial dataset of shipwreck location data.

Tap the ellipses (...) above your database instance in the UI and select "Load Sample Data."

tap the ellipses

A dialogue box will pop up with a link to the dataset and the option to load the data. Tap the green button to load the sample data into your database.

Load geospatial places collection

Get Started With MongoDB Compass

Let's get our Compass installed and set up. This will provide a nice GUI for interacting with our spatial data. It will also mean that we don't have to use the MongoDB shell or command line interface, which makes life easier.

Download Compass

Head to the MongoDB Compass download page and click the green "Download" button on the right to get the latest version.

A DMG will be downloaded to your computer. Open the DMG and drag the Mongo Compass icon into the Applications folder to install. Once it's installed, open the app.

Connect to Your Atlas Database

You'll see an option to create a New Connection. Rename the connection something like "Atlas Geospatial Data" and give it a color if you like.

Next, we'll need to edit the URI. Make sure that the "Edit Connection String" is toggled to the "ON" position, and delete the existing "mongodb://localhost:27017" string from the input box.

Next, head back to your Atlas page. Your sample dataset may still be loading. Click the "Connect" button just to the right of the connection name. A popup will appear with connection options.

MongoDB atlas connection options

Select "Connect Using MongoDB Compass" and choose "I have MongoDB Compass." Choose the version of Compass that you just installed from the dropdown, and copy the URL string in the provided text box.

Connect to MongoDB compass

Head back to your Compass app and paste the URL string into the input box. Hit "Connect." Make sure that the username and password for your Compass user are the same as the database user you created in your Atlas instance. If they are not, open the options for the connection and update the username and password to match what is in Atlas.

View Your GeoJSON Objects

On the left side should be a list of the collections of your sample data. Click on "sample_geospatial" and then expand "shipwrecks" to view the GeoJSON objects. Note that this sample data already contains geospatial indexes - MongoDB includes those for you.

A geojson object list

A geospatial index supports queries that calculate geometries on an earth-like sphere. In short, it allows you to run geospatial queries and do a geospatial search after you store geospatial data. It provides a set of geospatial query operators. Tap the "Indexes" tab to see the geospatial indexes.

Geospatial indexes (2dsphere index)

The 2dsphere index has already been added to each geojson point.

Perform Geospatial Queries

MongoDB provides several geospatial query operators that run against the geospatial index and let us do geospatial operations. Here are a few of the query operators:

  • $near - looks up dataset points near a given coordinates field.
  • $geoWithin - selects points within a specified shape
  • $geoIntersects - selects points that intersect a given geometry

Let's use the provided geospatial query operators to look up some points. The first thing we'll use is the $near operator to return a list of points near a given shipwreck.

We'll enter the query in the search bar at the top of the Compass UI. Here's the query:



   {
     coordinates:
       { $near:
          {
            $geometry: { type: "Point",  coordinates: [ -79.9081268, 9.3547792 ] },
            $minDistance: 1000,
            $maxDistance: 5000
          }
       }
   }

The above query looks for any records in the DB that have coordinates within a 1000-5000 mile radius of the given coordinates. The coordinates I used here came from the first entry in the collection. Make sure you get the 0 and the 1 position for the coordinates field correct.

The query returns a list of the records that match this criterion.

type point coordinates list

Conclusion

This was a very brief overview of how to get up and running with Geospatial queries against a sample dataset in MongoDB. We used MongoDB Atlas to create a cloud-hosted Mongo instance, which would allow us to store geospatial data from a sample dataset.

We then used MongoDB Compass to connect to the Atlas instance and look at the data. We viewed the geospatial index on each record which allows us to make geospatial queries.

Finally, we used the $near aggregator against the geospatial index to return a list of records that were near provided coordinate pairs.

FAQs

How Does MongoDB Store Location?

MongoDB allows you to store geospatial information as GeoJSON objects. These objects must include a coordinate field in [longitude, latitude] form where longitude must lie between [-180, 180] and latitude must lie between [-90,90].

There are multiple GeoJSON types: the GeoJSON point, linestring coordinates, polygon, multipoint, multilinestring, multipolygon, and geometrycollection.

Does MongoDB Support Geospatial?

Yes. MongoDB allows you to run a geospatial search and other geospatial operations against indexes on its geojson type.

Does MongoDB support GeoJSON?

Yes. MongoDB can store data as a GeoJSON type. It supports all seven GeoJSON types.

What Is Geospatial Index in MongoDB?

MongoDB's geospatial indexing allows you to efficiently execute spatial queries on a collection that contains geospatial shapes and points. The most common geospatial index is the 2dsphere index, which allows you to calculate geometries on an earth-like sphere. The 2dsphere index supports all MongoDB geospatial queries: inclusion, intersection, and proximity.

Abstract's IP Geolocation API comes with libraries, code snippets, guides, and more.

Get started for free
Abstract's IP Geolocation API comes with libraries, code snippets, guides, and more.
Get started