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):
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:
Also try
Site.distinct(:location)and look for any non-numeric data. (orSite.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: