EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials MongoDB Tutorial MongoDB Geospatial
Secondary Sidebar
MongoDB Tutorial
  • Advanced
    • MongoDB Array
    • PostgreSQL ARRAY_AGG()
    • Indexes in MongoDB
    • MongoDB create Index
    • MongoDB Collection
    • MongoDB List Collections
    • MongoDB Capped Collections
    • MongoDB Delete Collection
    • Mongodb show collections
    • MongoDB Auto Increment
    • MongoDB Triggers
    • MongoDB Projection
    • Replication in MongoDB
    • MongoDB Database
    • Mongo DB Create Database
    • MongoDB Compass
    • MongoDB Users
    • MongoDB Authentication
    • MongoDB GridFS
    • MongoDB Relationships
    • MongoDB MapReduce
    • MongoDB Geospatial
    • MongoDB Monitoring
    • Backup in MongoDB
    • MongoDB Sharding
    • MongoDB Java Drivers
    • MongoDB Import
    • Mongo Database Interview Questions
    • MongoDB Join Two Collections
    • MongoDB Group by Multiple Fields
    • MongoDB Pagination
    • MongoDB Replica Set
    • MongoDB Bulk Update
    • MongoDB greater than
    • MongoDB Encryption
    • MongoDB find in array
    • MongoDB like query
    • Mongodb shell
    • MongoDB port
    • MongoDB Query Operators
    • MongoDB Web Interface
    • MongoDB Query Array
    • MongoDB Transactions
    • MongoDB Not In
    • MongoDB not null
    • MongoDB npm
    • MongoDB Remove
  • Basics
    • What is MongoDB
    • How To Install MongoDB
    • MongoDB Tools
    • MongoDB GUI Tools
    • MongoDB Versions
    • MongoDB Commands
    • Advantages of MongoDB
    • MongoDB Features
    • Is MongoDB NoSQL
    • Is MongoDB Open Source
    • Build Web Applications using MongoDB
    • MongoDB Data Types
    • MongoDB Administration
    • Data Modeling in MongoDB
    • MongoDB vs Elasticsearch
    • MariaDB vs MongoDB
    • Firebase vs MongoDB
  • Commands
    • Mongodb updateMany
    • MongoDB Aggregation
    • Mongodb unwind
    • Mongodb where
    • MongoDB BSON
    • MongoDB Filter
    • Mongodb Match
    • MongoDB sort by date
    • MongoDB Limit()
    • MongoDB Atlas Login
    • MongoDB Relational Database
    • MongoDB count
    • MongoDB Aggregate
    • MongoDB Distinct
    • MongoDB Unique
    • MongoDB find
    • MongoDB findOne()
    • MongoDB insert
    • MongoDB Delete
    • MongoDB Update
    • Lookup in MongoDB
    • order by in MongoDB
    • MongoDB $regex
    • MongoDB $elemMatch
    • MongoDB ObjectId()
    • MongoDB Skip()
    • MongoDB findAndModify
    • Mongodb findOneAndUpdate
    • MongoDB Date Query
    • MongoDB Timestamp
    • MongoDB sort()
    • MongoDB group by
    • MongoDB Join

MongoDB Geospatial

By Sulaksh MoreSulaksh More

MongoDB Geospatial

Introduction to MongoDB Geospatial

MongoDB, which is a NoSQL Database, allows storing of Geospatial Data in the form of multiple GeoJSON types. Geospatial Feature of MongoDB makes it easy to store Geographical data into a database. So, basically, you can store the geospatial type data in the MongoDB in the form of GeoJSON objects. The GeoJSON is a simple representation of geographical features, also supporting non-spatial attributes, respectively. GeoJSON is based on JavaScript Object Notation and is an open standard format.

Syntax

"<field> : { type : <GeoJSON type> , coordinates : <coordinates> }"

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Explanation: <field> represents the name of the field, ex. Location: type is the key to which values could be different, ex—”Point” Type, which is commonly used. Finally, coordinates are the key which holds the longitude and latitude or other numeric details of the location. Now, let us understand the simple syntax with an example.

Code:

use geo
db.geo.insert( { "Name":  "Geo" } )
db.geo.insert( { Location : {"type":"Point","coordinates": [ 23.2222, 12.1111 ] } } )
db.geo.insert( { Location : {"type":"Point","coordinates": [ 31.1111, 21.3212 ] } } )
db.geo.find()

Output:

MongoDB Geospatial1

Explanation: Here, we are attempting to insert a single record in geo collection, which is a location and has a GeoJSON type as Point, followed by the coordinates. Check the below screenshot for proper execution:

Now that we have understood what Geospatial in MongoDB is let us look into operators available for Geospatial operations and understand them.

MongoDB Geospatial Operators

Operators in Geospatial for MongoDB can be divided into two parts which are Query Selectors and Geometry Specifiers. We will now understand each of there types, along with queries and examples. The Geometry Specifiers are used with the Query selectors so that we will learn these together. When we attempt any query selector, we have to specify a geometry specifier.

Note: We will be using important keywords like coordinates, Point, minDistance, maxDistance, geometry, etc., which are important when executing a query as these are the data point which stores the geospatial data.

MongoDB Geospatial Query Selectors

MongoDB provides four query selectors. These are operators used when we need to search or specify some data. For example, $near operator is used to return geo objects around the point. Following are the found query selectors:

$geoIntersects

Using the $geometry operator, geoIntersects operator specifies the GeoJSON Object. The 2dsphere and 2d indexes support these geoIntersect queries. With the following example, we will implement a simple $geoIntersect operator:

Code:

db.locs.find({ geometry: { $geoIntersects: { $geometry: { type: "Point", coordinates: [ -73.9341465567547, 40.819491095587647 ] } } } })

Output:

MongoDB Geospatial2

Explanation: we have our locs collection with 195 documents. We have specified the coordinates and will attempt to find the neighbourhood of a user. These return values might not make sense on the terminal, but it provides useful data when passed as raw data to a graphical representation.

Geometry Specifier For the use of Geospatial

Geometry Specifier used here is $geometry For the use of Geospatial Query Operators like $geoWithin, $geoIntersects, $near, and $nearSphere, $geometry is used. “EPSG:4326” is used as default CRS – coordinate reference system.

$geoWithin

This query selects the geometers which are bounded within the GeoJSON geometry. The 2dsphere and 2d indexes support $ geoWithin.

Code:

{
<location field>: {  $geoWithin: {
$geometry: { type: <"Polygon" or "MultiPolygon"> , coordinates: [ <coordinates> ] } }  }
}

Let us now understand $geoWithin with a proper example:

Code:

db.geo.find({ location: { $geoWithin: { $centerSphere: [ [ -73.934147654, 40.82302903 ], 2 / 1163.2 ] } } }).limit(2)

Output:

geoWithin

Explanation: We will attempt to find documents, using $geoWithin, which will return documents between the coordinates mentioned respectively. Refer the screenshot.

$near

This is also supported by both indexes and is used to return the geospatial object near a specific point. This returns a stored document by nearest to farthest from a point.

Code:

{
<location field>: {  $near: {
$geometry: { type: "Point" , coordinates: [ <longitude> , <latitude> ] },
$maxDistance: <distance in meters>, $minDistance: <distance in meters> }   }
}

We will now implement $near with an example and see its working.

Code:

db.area.find({location :{$near :{$geometry :{coordinates :[31.11,43.21]}}}})

Output:

near

Explanation: This query will return several documents with coordinates nearby the mentioned ones.

$nearSphere

This query returns the documents from a collection, which lies nearest to farthest. MongoDB uses spherical geometry to calculate the distance. Geospatial index is required with $nearSphere.

Code:

{
$nearSphere: { $geometry: { type : "Point", coordinates : [ <longitude>, <latitude> ] },
$minDistance: <distance in meters>,  $maxDistance: <distance in meters> }
}

Code:

db.area.find({location :{$nearSphere :[31.11,43.22]}})

Output:

MongoDB Geospatial5

Explanation: This query will return several documents which match with the coordinates provided. Refer the below-attached screenshot for proper output. Let us now understand the geometry specifiers. We have already learned $geometry, remaining will be $center, $maxDistance, $minDistance, $polygon and $box.

$center

for $geoWithin query, $center specifies a circle. This operator DOES NOT return an object of GeoJSON.

Code:

db.area.find({location:{$geoWithin:{$center:[[-31,33],20]}}})

Output:

MongoDB Geospatial6

Explanation: Here, we have used the $center query with $geoWithin. Refer the screenshot.

$minDistance

Below we have a simple example of $minDistance.

Code:

db.area.findOne({location :{$nearSphere :{$geometry : {coordinates :[31.11,43.22]},$minDistance: 10}}})

Output:

minDistance

$polygon

Used with $geoWithin, returns documents which fall between the bound of a polygon. Does NOT query GeoJSON. Without a geospatial index, $polygon can be used, but queries can be executed faster with geospatial index rather than unindexed. Supported only with 2d geospatial index.

$box

which attempts to specify a rectangle for $geoWithin, and when used in a query, it finds the documents with coordinates falling between the rectangle. $box is supported only with 2d geospatial index. Using Flat Geometry, this query calculates the distance.

Conclusion

MongoDB Geospatial is used to store geographical data, like location coordinates. Multiple types of GeoJSON are supported. There are two types of queries, which are Query Selectors and  Geometry Specifiers. MongoDB supports 7 types of GeoJSON Objects, Point being the most common one. We learned and understood each operator along with example and code, respectively.

Recommended Articles

This is a guide to MongoDB Geospatial. Here we discuss an introduction to MongoDB Geospatial, appropriate syntax, operators, and examples. You can also go through our other related articles to learn more –

  1. What is MongoDB?
  2. MongoDB Tools
  3. MongoDB Alternatives
  4. Guide to MongoDB Data Types
  5. MongoDB count | How to Works?
  6. MongoDB Delete | How to Work?
  7. Guide to MongoDB Array
Popular Course in this category
MongoDB Training Program (4 Courses, 2 Projects)
  4 Online Courses |  2 Hands-on Projects |  22+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Oracle Training (17 Courses, 8+ Projects)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
SQL Training Program (10 Courses, 8+ Projects)4.7
Oracle DBA Database Management System Training (2 Courses)4.7
MS SQL Training (16 Courses, 11+ Projects)4.7
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more