Ruby on rails 使用Mongoid在MongoDB中查询多个位置

Ruby on rails 使用Mongoid在MongoDB中查询多个位置,ruby-on-rails,mongodb,mongoid,geospatial,Ruby On Rails,Mongodb,Mongoid,Geospatial,我正在尝试使用空间索引查询文档 根据我的模型看起来像: class Trip include Mongoid::Document field :addresses, :type => Array index({"addresses.loc" => "2d"}, {:min => -180, :max => 180}) end 加法是这样存储的 Trip.first.addresses => [{"context"=>"from", "loc"=&

我正在尝试使用空间索引查询文档

根据我的模型看起来像:

class Trip
  include Mongoid::Document
  field :addresses, :type => Array
  index({"addresses.loc" => "2d"}, {:min => -180, :max => 180})
end
加法是这样存储的

Trip.first.addresses
=> [{"context"=>"from", "loc"=>[-71.55234, -33.024527]}, {"context"=>"to", "loc"=>[-70.641997, -33.4691199]}]
我想使用此查询查询与address.loc和address.context匹配的文档:

Trip.where("addresses.loc" => {"$nearSphere" => [-70.641997, -33.4691199], "$maxDistance" => 0.005052092295133236}).where("addresses.context" => "to")
查询返回正确的值,但似乎忽略了“address.context”。 我在用正确的方法做吗


谢谢

要查找数组与表达式匹配的文档,应使用#elem_match:

Trip.elem_match(addresses: {context: 'to', _rest_of_your_geospatial_stuff_ })
请在此处阅读更多信息:


顺便说一句,为什么不为“from”和“to”位置创建单独的字段并简化操作?因为“二维索引不支持文档中的多组坐标”公平点。但是:“2.0版新增:支持文档中的多个位置。”是的,但您不能指定搜索特定上下文,对吗?我不知道。请让我知道elem#u match是否解决了您的问题。