“在X英里内”搜索mongodb

时间:2011-08-09 05:50:02

标签: nosql mongoid

我希望能够找到与其他邮政编码在特定半径范围内的邮政编码。我有一些来自this source的代码。但它是使用ActiveRecord的SQL实现。这正是我想要的实现,但仅限于MongoDB。救命啊!

1 个答案:

答案 0 :(得分:3)

查看MongoDB documentation和Mongoid indexing docs

class Zip
  include Mongoid::Document
  field :code
  field :location, :type => Array

  # make sure to rake db:mongoid:create_indexes
  index [[ :location, Mongo::GEO2D ]], :min => 200, :max => 200
end

# at the console
Zip.create(:code => 1001, :location => [0, 0])
Zip.create(:code => 1002, :location => [1, 1])
Zip.create(:code => 1003, :location => [2, 1])
Zip.create(:code => 1004, :location => [-1, -1])

Zip.where(:location => { '$near' => [0, 0] } ).count
# 4
Zip.where(:location => { '$near' => [0, 0], '$maxDistance' => 1.5 } ).count
# 3
Zip.where(:location => { '$near' => [0, 0], '$maxDistance' => 1 } ).first
# 1