2011-08-09 11 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 
関連する問題