MongoDB: Geospatial Data and Views

Posted on Oct 13, 2017

MongoDB: Geospatial Data and Views

MongoDB is a very famous Nosql database and there are various blogs that showcase, the goodness of mongodb. In this blog, I want to highlight some features of mongodb that may be new to some readers.


Geolocation data with MongoDB: 

We can save geolocation(Geospatial) data using GeoJson Objects. For example:

geoLocation: {
    type: "Point",
    coordinates: [-73.856077, 40.848447]

Above is an example of GeoJson Object namely GeoJson Point. Here we require following:

  • Type field that specifies GeoJson type, can be: LineString, Polygon,  GeometryCollection etc. For more, refer here.
  • Coordinates field that includes latitude and longitude
  • geoLocation is the field name.

The actual query is:

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

For more details, refer here.


  • No physical schema and no use of disk space.
  • Always read-only, write operations on views will throw an error.
  • Always execute a pre-defined query
  • Which makes it easier to fetch data
  • It adds a layer of abstraction and helps in data security


db.createView(<view>, <source>, <pipeline>, <options>)

View – name of view
Source – name of source collection
Pipeline – An array that consists of the aggregation pipeline. View is being created by applying the pipeline to source collection.
Options – Additional option

  [{ $project : 
    { _id : 0, address : {$concat : ["$address1", " ","$address2"]}}

In this example, we are going to focus on one field i.e address, which is a combination of values stored in address1 and address2 so whenever we run the find query:


The result set will show an address field, instead of 2 separate fields i.e. address1 and address2.

So the good thing about view is, It allows us to customize the resultant fields and we can perform the needed sort etc operation to get the desired results.

More can be read from here.

I hope, i was able to give a basic idea about handling geolocation data as well as views.