使用 mongoid 在范围内查找不同的行 [英] Finding distinct rows in scope with mongoid

查看:55
本文介绍了使用 mongoid 在范围内查找不同的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 rails 项目中有两个模型:persons 和一个嵌入式集合,城市.还有一个关于城市的空间索引.我想找到一个城市附近的所有人.

I have two models in my rails project: persons and an embeded collection, cities. there is also a spatial index on the cities. I want to find all persons near one city.

class Person
 include Mongoid::Document
 include Mongoid::Timestamps
 embeds_many :cities
 scope :nearby, ->(location, distance) { where('cities.location' => 
                    {'$near' => location , '$maxDistance' => distance})}


class City
  include Mongoid::Document
  include Mongoid::Timestamps
  embedded_in :person
  field :city
  field :location, type: Array  #0: latitude, 1: longitude

location_in_new_york = [40.71892, -74.00131]

我的查询是

Person.nearby(location_in_new_york, 1)

但是这样做一个拥有两个彼此非常接近的城市的人会被发现两次.我怎样才能避免这种行为?我不想在 ruby​​ 中减少这个,因为我想保持我的范围.

But doing so a person with two cities which are very close to each other get found twice. How can I avoid this behavior? I dont want to reduce this in ruby, because I would like to keep my scope.

推荐答案

虽然不像能够根据条件调用 .distinct 那样干净,但此解决方法提供了预期的结果:

While not as clean as just being able to call .distinct on a criteria, this workaround gives the expected results:

Person.find(Person.nearby(location_in_new_york, 1).distinct(:_id))

然而,这不能(如所写)作为作用域,因此您必须将其设为类方法.就个人而言,我会考虑向 mongoid 添加一个补丁来添加一个 .unique 方法来执行您想要的操作(因为当您使用其不同的运算符时,MongoDB 负责返回字段值而不是文档:http://www.mongodb.org/display/DOCS/Aggregation )

This doesn't work (as written) as a scope, however, so you'd have to make it a class method. Personally, I would look into adding a patch to mongoid to add a .unique method that does what you want (since MongoDB is responsible for returning field values instead of documents when you use its distinct operator: http://www.mongodb.org/display/DOCS/Aggregation )

这篇关于使用 mongoid 在范围内查找不同的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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