首页 文章

Mongoid范围检查数组字段是否包含值

提问于
浏览
19

这个问题的解决方案可能看起来很简单,但我一直挥手无言 .

我在 Rails 4.1.4 app中使用了 Mongoid . 我有一个模型,其中包含一个将包含字符串值的数组字段 .

我需要模型中的 Mongoid's 范围来检索这个Array字段包含特定String值的实例,该值作为范围的参数给出 . 假设我们有这个模型:

class SomeModel
  include Mongoid::Document
  include Mongoid::Timestamps

  field :some_array, type: Array, default: Array.new

  scope :some_scope, ->(value){ elem_match(some_array: value) }

end

上述范围不起作用,因为显然在 MongoDB $ elemMatch需要接收 Criteria 作为值 . 但是, Criteria 如何只是说元素必须等于给定的值??? .

关于如何编写这个非常简单的范围的任何线索???

问候!!! . 提前致谢 .

1 回答

  • 31

    你是一个过于复杂的事情 . 如果一个字段包含一个数组,那么你可以搜索它,就像它不是一个数组一样 . 例如,如果您在文档中有此:

    { some_array: [ 'where', 'is', 'pancakes', 'house?' ] }
    

    你做这样的查询:

    where(:some_array => 'pancakes')
    

    你需要'll find that document. You don'或其他任何复杂的东西;你可以假装数组是简单查询的单个值,就像你有:

    scope :some_scope, ->(value) { where(:some_array => value) }
    

    如果要将多个条件应用于数组的每个元素,您只需要进入 $elemMatch ,这样的事情来自 $elemMatch docs:

    results: { $elemMatch: { $gte: 80, $lt: 85 } }
    // ^^^^^^^array           ^^^^^^^^^^^^^^^^^^^^^multiple conditions
    

    不要心疼,目前的MongoDB文档对这些内容并不十分清楚(或者至少我找不到明确的解释) .

相关问题