Geospatial Query results in exception "geo field only has 1 element"

428 views
Skip to first unread message

Joe Busuttil

unread,
Apr 8, 2013, 2:08:00 AM4/8/13
to mongo...@googlegroups.com
Hi and thanks for reading. I'm quite new to Ruby and Mongomapper so please forgive me if this is obvious.

I'm trying to do a geospatial query, depending on how the user enters their location it'll either be an exact match or distance based. I'd like to also query with other fields.

The Model
class User
  include MongoMapper::Document
  #other fields removed for brevity
  key :location, Array
  ensure_index [[:location, '2d']]
  key :locationname, String
  key :geosearchtype, String
  key :searchdistance, Integer, :default => 1
  key :active, String, :default => "on"
  key :visible, Boolean, :default => false
  timestamps!
end

The location is set by a query to google through the geocoder gem

In the mongo client I am able to do:
db.users.find({location: [-31.945475, 115.8566411], active: "on", visible: true})
and this gives me three results

In MongoMapper I'm doing (some lines commented out to make things simpler:

if @user.visible == true
      basequery = Hash.new
     # basequery["visible"] = true
     # basequery["active"] = "on"
      if @user[:geosearchtype] == "venue"
        basequery["location"] = @user[:location]
      elsif @user[:geosearchtype] == "distance"
         basequery[:location] =  {'$near' => @user[:location], '$maxDistance' => @user[:searchdistance]})
      end
      @matchedusers = User.where(basequery).all
end

I've only tested with the Exact match (ie venue based) and when I do I get:
geo field only has 1 element

Since my query works in mongo I don't understand what I need to do differently in MongoMapper. Any help would be appreciated.

Joe Busuttil

unread,
Apr 9, 2013, 10:30:09 PM4/9/13
to mongo...@googlegroups.com
I found a solution, it seems that you need a way to tell MongoMapper/Plucky/MongoDB that I'm using an array in the query, the way I was doing things my query term was being treated as a single item, hence the "geo field has only 1 element". I changed my query to:

        @basequery["location.0"] = @user[:location][0]
        @basequery["location.1"] = @user[:location][1]

and it works great, now to try and work out how to wrangle this into a $near query...
Reply all
Reply to author
Forward
0 new messages