如何使用Ruby on Rails – Mongoid进行嵌入式位置查询?
- 内容介绍
- 文章标签
- 相关推荐
本文共计342个文字,预计阅读时间需要2分钟。
我有一个模型:`City` 类继承自 `Mongoid::Document`,包含字段 `name` 和嵌入的 `stores`,使用 `index` 为 `[[stores.location], Mongoid::Geo2D]]`。`Store` 类也继承自 `Mongoid::Document`,包含字段 `name`、`location` 和 `type`(数组类型),并且嵌入在 `cities` 中。
我有一个模型:class City include Mongoid::Document field :name embeds_many :stores index [["stores.location", Mongoid::GEO2D]] end class Store include Mongoid::Document field :name field :location, :type => Array embedded_in :cities, :inverse_of => :stores end
然后我尝试调用类似City.stores.near(@location)的东西.
我想查询City集合以返回在附近位置至少有1个商店的所有城市.我该如何设置索引?什么是最快的电话?
我使用索引[[:location,Mongo :: GEO2D]]阅读了Mongoid文档,但我不确定这是如何应用于嵌入式文档,或者如何仅获取City而不是所有Stop文档.
麦克风,您请求的功能称为多位置文档.目前的稳定版本1.8.2不支持它.这仅适用于1.9.1版.
使用mongoid时查询很简单,就像这样
City.near("stores.location" => @location)
在多位置文档中使用近查询时要小心,因为同一文档可能会多次返回,因为$near查询会按距离返回有序结果.您可以阅读有关此here的更多信息.
在查询中使用$来获得正确的结果
使用$within和$centerSphere编写的相同查询
EARTH_RADIUS = 6371 distance = 5 City.where("stores.location" => {"$within" => {"$centerSphere" => [@location, (distance.fdiv EARTH_RADIUS)]}})
本文共计342个文字,预计阅读时间需要2分钟。
我有一个模型:`City` 类继承自 `Mongoid::Document`,包含字段 `name` 和嵌入的 `stores`,使用 `index` 为 `[[stores.location], Mongoid::Geo2D]]`。`Store` 类也继承自 `Mongoid::Document`,包含字段 `name`、`location` 和 `type`(数组类型),并且嵌入在 `cities` 中。
我有一个模型:class City include Mongoid::Document field :name embeds_many :stores index [["stores.location", Mongoid::GEO2D]] end class Store include Mongoid::Document field :name field :location, :type => Array embedded_in :cities, :inverse_of => :stores end
然后我尝试调用类似City.stores.near(@location)的东西.
我想查询City集合以返回在附近位置至少有1个商店的所有城市.我该如何设置索引?什么是最快的电话?
我使用索引[[:location,Mongo :: GEO2D]]阅读了Mongoid文档,但我不确定这是如何应用于嵌入式文档,或者如何仅获取City而不是所有Stop文档.
麦克风,您请求的功能称为多位置文档.目前的稳定版本1.8.2不支持它.这仅适用于1.9.1版.
使用mongoid时查询很简单,就像这样
City.near("stores.location" => @location)
在多位置文档中使用近查询时要小心,因为同一文档可能会多次返回,因为$near查询会按距离返回有序结果.您可以阅读有关此here的更多信息.
在查询中使用$来获得正确的结果
使用$within和$centerSphere编写的相同查询
EARTH_RADIUS = 6371 distance = 5 City.where("stores.location" => {"$within" => {"$centerSphere" => [@location, (distance.fdiv EARTH_RADIUS)]}})

