“在X英里内"在mongodb中搜索 [英] "Within X miles" search in mongodb

查看:53
本文介绍了“在X英里内"在mongodb中搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够找到距另一个邮政编码特定距离范围内的邮政编码.我有一些来自此来源的代码.但这是使用ActiveRecord的SQL实现.正是我想要的实现,但仅适用于MongoDB.救命!

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!

推荐答案

看看MongoDB 索引文档.

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

这篇关于“在X英里内"在mongodb中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆