“Within X miles” search in mongodb

匆匆过客 提交于 2019-12-07 13:51:31

问题


I want to be able to find zip codes are that within a specific radius of distance from another zip code. I have some code from this source. But it is an SQL implementation using ActiveRecord. It is precisely the implementation I want but only with MongoDB. Help!


回答1:


Take a look at the MongoDB documentation and the 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


来源:https://stackoverflow.com/questions/6991893/within-x-miles-search-in-mongodb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!