2011-08-09 58 views
3

我希望能夠找到的郵政編碼是距離另一個郵政編碼的特定半徑範圍內。我有一些代碼從this source。但它是使用ActiveRecord的SQL實現。這正是我想要的實現,但僅限於MongoDB。幫幫我!「在X英里內」在mongodb中搜索

+1

你應該看看mongoid-geo gem。 https://github.com/kristianmandrup/mongoid-geo – rubish

+1

截至2011年8月,該鏈接項目似乎已停止開發。相反,你可能想看看https://github.com/ryanong/mongoid_spacial。 – Matt

回答

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