MongoDB with Mongoid in Rails - Geospatial Indexing

MongoDB has a very nice Geospatial Indexing feature. How can I use it in Rails with Mongoid?

Answers


You can define geo indexes like this in mongoid

class Item
  include Mongoid::Document

  field :loc, :type => Array

  index(
      [
          [:loc, Mongo::GEO2D]             
      ], background: true

  )
end

And for queries

$near command (without maxDistance)

 location = [80.24958300000003, 13.060422]
 items = Item.where(:loc => {"$near" => location})

$near command (with maxDistance)

 distance = 10 #km
 location = [80.24958300000003, 13.060422]
 items = Item.where(:loc => {"$near" => location , '$maxDistance' => distance.fdiv(111.12)})

Convert distance by 111.12 (one degree is approximately 111.12 kilometers) when using km, or leave distance as it is on using degree

$centerSphere / $nearSphere queries

location = [80.24958300000003, 13.060422]
items = Item.where(:loc => {"$within" => {"$centerSphere" => [location, (distance.fdiv(6371) )]}})

This will find the items within the 10 km radius. Here we need to convert the distance/6371(earth radius) to get it work with km.

$box (bounding box queries)

 first_loc = [80.24958300000003, 13.060422]
 second_loc = [81.24958300000003, 12.060422]
 items = Item.where(:loc => {"$within" => {"$box" => [first_loc, second_loc]}})

This will help you to find the items within the given bounding box.


RameshVel's answer is great.

As an update, in Mongoid 3.0.4, I had to define the index as follows to make it work with rake db:mongoid:create_indexes:

index(
  { loc: Mongo::GEO2D },
  { background: true }
)

All those answers are a outdated with newest versions of MongoDB and will throw some uninitialized constant Mongo::GEO2D

For mongoid 4/5, I suggest you have look at the mongoid-geospatial gem if you need to play with 2D Objects or coordinates.


Need Your Help

How to Get E commerce Applications Data other than API?

api web-scraping e-commerce amazon-mws amazonsellercentral

I am just wondering to know that is there are other techniques available to access or fetch the data that data is not provided by the API like Flipkart sellers Orders API doesn't provide image in his

How to bind variables into websocket route paths using Spark Web Framework?

java path websocket routes spark-java

I'm, trying to implement a websocket server using Spark (a java web framework). I'm using the version 2.3 that has added support for it.