Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoMapper near with maxDistance - Mongo::OperationFailure: geo values have to be numbers:

I'm trying to encapsulate a near query with a maxDistance in a MongoMapper backed model.

I must be doing something silly in my query syntax.

Model

class Site
  include MongoMapper::Document

  key :id, Integer 
  key :name, String
  key :location, Array
  ensure_index [[:location, '2d']]


  def self.nearest(center_point, range)
    where(:location => {'$near' => center_point, '$maxDistance' => range}).all
  end

end

Trying to get everything within 200 miles of a point...

Site.nearest([-122.0,44.0],200)

> Mongo::OperationFailure: geo values have to be numbers: {
> $maxDistance: 200, $near: [ -122.0, 44.0 ] }  from
> /Library/Ruby/Gems/1.8/gems/mongo-1.6.1/lib/mongo/cursor.rb:144:in
> `next'    from
> /Library/Ruby/Gems/1.8/gems/mongo-1.6.1/lib/mongo/cursor.rb:290:in
> `each'    from
> /Library/Ruby/Gems/1.8/gems/mongo-1.6.1/lib/mongo/cursor.rb:308:in
> `to_a'    from
> /Library/Ruby/Gems/1.8/gems/mongo-1.6.1/lib/mongo/cursor.rb:308:in
> `to_a'    from
> /Library/Ruby/Gems/1.8/gems/plucky-0.4.4/lib/plucky/query.rb:74:in
> `all'     from /Users/nick/Code/web/map/app/models/site.rb:40:in
> `nearest'     from (irb):
like image 456
Nick Avatar asked Dec 10 '22 01:12

Nick


2 Answers

You may have run into this bug that requires $near and $maxDistance to be ordered with $maxDistance first.

In any case, I found this question because I was getting OperationFailure: database error: geo values have to be number when using PyMongo, and swapping the order fixed it.

like image 78
David Johnstone Avatar answered May 16 '23 08:05

David Johnstone


I'm guessing it's actually a data problem or index problem, your query looks correct.

See http://www.mongodb.org/display/DOCS/Geospatial+Indexing ... MaxDistance of 200 may be too large:

By default, the index assumes you are indexing longitude/latitude and is thus configured for a [-180..180) value range.

The distance unit is the same as in your coordinate system.

Also try Site.distinct(:location) and look for any non-numeric data. (or Site.query.distinct(:location) if you're not on MM 0.11.1).

Hint: If you want to see what a query is going to look like when it hits MongoDB, add .criteria.to_hash:

Site.where(:location => {'$near' => center_point, '$maxDistance' => range}).criteria.to_hash
# =>
{
  :location=> {
    "$near"        => [-122.0, 44.0],
    "$maxDistance" => 200
  }
}
like image 29
Brian Hempel Avatar answered May 16 '23 08:05

Brian Hempel