| by Arround The Web | No comments

How to Implement MongoDB Geospatial Features

The geospatial feature of MongoDB provides a straightforward way to store the geographic data in a database. Essentially, we can store the geospatial data in MongoDB as GeoJSON objects. GeoJSON is a free and open-source format that depends on the JavaScript Object Notation with simple geographical data. This functionality is important for apps that require services based on location such as the mapping process, based on location search, and others. This article covers the geospatial feature with the example implementation.

Adding Documents into the Collection for Geospatial Features

To demonstrate the functionality of the MongoDB Geospatial feature, we need the documents for the specific collection. We insert a few documents into the “area” collection as shown in the following:

db.area.insertMany( [
   {
      name: "Children Park",
      location: { type: "Point", coordinates: [ -60.97, 30.77 ] },
      category: "Garden"
   },
   {
      name: "Student Area",
      location: { type: "Point", coordinates: [ -60.9928, 30.7193 ] },
      category: "Garden"
   },
   {
      name: "FootBall Ground",
      location: { type: "Point", coordinates: [ -60.9375, 30.8303 ] },
      category: "Stadium"
   }
] )

We have documents that contain the location data such as coordinates. Additionally, we create a geospatial index on the field to optimize the performance of geospatial queries.

Example 1: Using the $geoIntersects Query Operator

First, we have the geospatial feature’s $geoIntersects operator which intersects with the provided object. Consider the following implementation of the $geoIntersects operator:

db.area.find({ location: { $geoIntersects: { $geometry: { type: "Point",

coordinates: [ -60.97, 30.77 ] } } } })

In the example, we call the “area” collection along with the “find” operation. To the find() method, we pass the “location” field sets to the $geoIntersects query operator of the geospatial feature. This is used to check if the specified point intersects with the geometry that is stored in the geometry field.

Then, the $geoIntesects operator takes the $geometry operator where the type field is set with the “Point” value and the coordinates field is given with the “coordinates” values. Here, the $geometry is defined for the geospatial comparison.

The following output is where the expected document is retrieved and where the geometry field contains a geometric object that intersects with the specified point:

Example 2: Using the $near Query Operator

The $near operator is also the geospatial feature that is used to do the geospatial queries to identify the documents that are geographically near to a given place. It retrieves the documents that are arranged according to their proximity to the specified location. Here, we provide the implementation of the $near operator:

db.area.find(
   {
     location:
       { $near :
          {
            $geometry: { type: "Point",  coordinates: [ -60.9667, 30.78 ] },
            $minDistance: 1000,
            $maxDistance: 5000
          }
       }
   }
)

In the example, we define the “location” field of the “area” collection inside the “find” operation. Then, we set the $near query operator of the geospatial feature to that “location” field. The $near operator searches for the near point with the given coordinates point. Next, we use the $minDistance and $maxDistance parameters in the $near operator which are provided with certain values to retrieve the documents within the specified distance range from the given point.

The document is retrieved in the output that is near the specified locations or points of interest in a geospatial “area” collection:

Example 3: Using the $nearsphere Query Operator

Alternatively, we have the $nearsphere operator which is similar to the $near operator, but $nearSphere takes into account the spherical shape of the Earth when calculating the distances.

db.area.find(
   {
     location: {
        $nearSphere: {
           $geometry: {
              type : "Point",
              coordinates : [ -60.9667, 30.78 ]            },
           $minDistance: 1000,
           $maxDistance: 5000
        }
     }
   }
)

In the example, we use the $nearsphere operator of the geospatial query. The $nearspehere operator here searches for the document whose nearest points are close to the points that are specified in the query, and the points are set to the coordinate field array.

After that, we refine the results by establishing the $minDistance and $maxDistance parameters. The $minDistance parameter ensures that the returned documents are at least 1000 meters away from the specified point, while the $maxDistance parameter limits the results to the locations that are no more than 5000 meters away.

The document is displayed in the output with a location within a specified meter from the point with given coordinates:

Example 4: Using the $geoWithin Query Operator

Next, we have the $geoWithin operator in MongoDB which is used for geospatial queries to find the documents that are completely within a specified shape such as a circle. Let’s have the following demonstration of the $geoWithin query:

db.area.find({ location:

{ $geoWithin:

{ $centerSphere: [ [ -60.93414657, 30.82302903 ], 3/3963.2 ] } } })

In the example, we use the $geoWithin operator to find the documents of the “area” collection within a certain circular area on a 2D sphere. For this, we specify the $centerSphere operator inside the $geoWithin operator which takes the two arguments as the centric point, which likely represents the coordinates point here, and the circle’s radius which represents the distance value in miles.

The resultant document is retrieved in the following which represents a geospatial point that falls within the circle that is defined by the given center point and the radius of approximately 3 miles:

Example 5: Using the $geoNear Query Operator

Moreover, the $geoNear operator is also a geospatial operator which is used for the aggregation pipeline. It performs a geospatial query and returns the documents that are sorted by their proximity to a specified point. Here, we have given the $geoNear operator which is called inside the aggregation pipeline.

db.area.aggregate([
   {
     $geoNear: {
        near: { type: "Point", coordinates: [ -60.99279 , 30.719296 ] },
        distanceField: "dist.calculated",
        maxDistance: 2,
        query: { category: "Garden" },
        includeLocs: "dist.location",
        spherical: true
     }
   }
])

In the example, we call the aggregate method of MongoDB and define the $geoNear operator inside it. The $geoNear operator is set with several parameters to specify the query behavior. First, we set the “near” parameter which provides the “coordinates” values as a reference point to search.

Then, we utilize the “distanceField” parameter to specify the provided field as the outcome field. This set outcome field stores the distance between each document and the reference point. Next, we define the “maxDistance” parameter with the value of “2″ which represents the maximum distance in meters.

After that, we have the “query” parameter which filters the documents by the “category” field and only considers the documents where the “category” is “Parks”. We then call the “includeLocs” parameter to contain the location information. We finally specify the “spherical” parameter with the “true” value which calculates the distances using a 2D spherical coordinate system.

The aggregation pipeline represents the document in the output which displays the information against the parameter accordingly. The following “dist.calculated” field displays the distance of each document from the reference point:

Conclusion

We came to know that the geospatial capabilities of MongoDB help us to efficiently handle and query the location-based information. We learned the implementation of the geospatial feature using its various operators with the example program. We have many more functionalities and methods which are also beneficial for a wide range of applications.

Share Button

Source: linuxhint.com

Leave a Reply