Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learning Mongoid

You're reading from   Learning Mongoid If you know MongoDB and Ruby, then Mongoid is a very handy tool to have at your disposal. Quickly learn to build Rails applications with the helpful code samples and instructions in this book.

Arrow left icon
Product type Paperback
Published in Dec 2013
Publisher Packt
ISBN-13 9781782167501
Length 140 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Gautam Rege Gautam Rege
Author Profile Icon Gautam Rege
Gautam Rege
Arrow right icon
View More author details
Toc

Geolocation queries


Geolocation is in-built into MongoDB, and is one of its distinguishing features. We have seen examples of 2d or 2dsphere index in earlier chapters, and also seen how we can use the near criterion. Using $geoNear, that is, the geo_near method we can get geospatial criteria easily.

One of the common problems in geospatial search is that the queries use radians and not distance units (kilometers, or miles). MongoDB provides a distanceMultiplier operator that we can use to ensure consistency.

So, this query will give results with the distance in miles:

Author.geo_near([ 50, 13 ]).distance_multiplier(3959)

Tip

The earth has a radius of approximately 3,959 miles or 6,371 km.

Suppose, we find all authors within a 10 miles radius of [34.052923, -84.44399]. First and foremost, when using only latitude and longitude, using a 2dsphere index is recommended. So, let's modify the Author model.

class Address
  include Mongoid::Document
  ...

 field :location, type: Array  # the location co...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image