【问题标题】:"Within X miles" search in mongodb在 mongodb 中搜索“X 英里内”
【发布时间】:2011-08-09 05:50:01
【问题描述】:

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

【问题讨论】:

标签: nosql mongoid


【解决方案1】:

看看 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 2011-07-29
    • 1970-01-01
    • 2012-11-29
    • 2019-11-26
    • 1970-01-01
    相关资源
    最近更新 更多