gpt4 book ai didi

ruby-on-rails - Mongoid 和查询嵌入式位置?

转载 作者:可可西里 更新时间:2023-11-01 09:23:45 28 4
gpt4 key购买 nike

我有一个模型:

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 个 Store 的所有城市。我应该如何设置索引?最快的调用是什么?

我使用 index [[:location, Mongo::GEO2D]] 阅读了 Mongoid 文档,但我不确定这如何应用于嵌入式文档,或者如何只获取 City 而不是所有的 Stop 文档。

最佳答案

迈克,

您请求的功能称为多位置文档。当前稳定版本 1.8.2 不支持它。这仅适用于版本 1.9.1。

而且使用mongoid查询起来很简单,就是这样

   City.near("stores.location" =>  @location)

并且在多位置文档中使用 near 查询时要小心,因为同一个文档可能会返回多次,因为 $near 查询返回按距离排序的结果。您可以阅读更多相关信息 here .

改用 $within 查询以获得正确的结果

使用 $within 和 $centerSphere 编写的相同查询

EARTH_RADIUS = 6371
distance = 5
City.where("stores.location" => {"$within" => {"$centerSphere" => [@location, (distance.fdiv EARTH_RADIUS)]}})

关于ruby-on-rails - Mongoid 和查询嵌入式位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6655606/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com