Book Image

Learning Mongoid

By : Gautam Rege
Book Image

Learning Mongoid

By: Gautam Rege

Overview of this book

Mongoid helps you to leverage the power of schema-less and efficient document-based design, dynamic queries, and atomic modifier operations. Mongoid eases the work of Ruby developers while they are working on complex frameworks. Starting with why and how you should use Mongoid, this book covers the various components of Mongoid. It then delves deeper into the detail of queries and relations, and you will learn some tips and tricks on improving performance. With this book, you will be able to build robust and large-scale web applications with Mongoid and Rails. Starting with the basics, this book introduces you to components such as moped and origin, and how information is managed, learn about the various datatypes, embedded documents, arrays, and hashes. You will learn how a document is stored and manipulated with callbacks, validations, and even atomic updates. This book will then show you the querying mechanism in detail, right from simple to complex queries, and even explains eager loading, lazy evaluation, and chaining of queries. Finally, this book will explain the importance of performance tuning and how to use the right indexes. It also explains MapReduce and the Aggregation Framework.
Table of Contents (14 chapters)
Learning Mongoid
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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...