如何使用可以引用 mongodb 中对象数组的字段制作红宝石模型



我正在用 ruby 制作一个模型,就像我在下面分享的那样。问题是我需要在过滤器的位置引用键值对。那么我应该怎么做呢?

class User
 include Mongoid::Document
 store_in collection: "user"
 field :name, type: String
 field :number, type: String
 field :locations #is an array of locations with key-value pairs
end

例如,用户对象类似于

db.user.findOne()
{
 "name" : "ABC",
 "number" : "1234567890",
 "locations" : [
    {
        "state" : "X",
        "district" : "AY",
    },
    {
        "state" : "V",
        "district" : "BZ",
   }
 ],
}

使用过滤器,我需要找到所有处于所述状态="X"的用户。Mongo查询将使用locations.state,但如何定义一个可以帮助查询此类状态的字段。为了在过滤器中查询,我正在使用活动管理员,如下所示:

filter :locations, label: 'Locations', as: :select,
     collection: {
         'x': 'X',
         'v': 'V',
     }

因此,我需要一种方法来查询位置而不是位置中的状态。有关如何解决此问题的任何帮助都将非常有帮助。

如果需要任何其他详细信息,请告诉我。

提前感谢!

有几种方法可以做到这一点:

1. 使用数组类型

class User
  include Mongoid::Document
  store_in collection: "user"
  field :name, type: String
  field :number, type: String
  field :locations, type: Array
end

2. 使用嵌入的文档

class User
  include Mongoid::Document
  store_in collection: "user"
  field :name, type: String
  field :number, type: String
  embeds_many :locations
end
class Location
  include Mongoid::Document
  field :state, type: String
  field :district, type: String
  embedded_in :user  
end

这里的主要优点是,您可以将适当的业务逻辑放在Location模型上,而不是膨胀User模型。

3. 使用参考文档

class User
  include Mongoid::Document
  store_in collection: "user"
  field :name, type: String
  field :number, type: String
  has_and_belongs_to_many :locations
end
class Location
  include Mongoid::Document
  field :state, type: String
  field :district, type: String
  has_and_belongs_to_many :users
end

这有点像 #2,但允许您使用规范化文档作为位置,而不是为每个用户复制它们。这在早期版本的Mongoid(和MongoDB(中有点性能问题,因为没有join支持。

最新更新