这个问题的解决方案可能看起来很简单,但我一直在挥舞着没有答案。
我在我的 Rails 4.1.4 应用中使用 Mongoid。我有一个模型,其中包含一个 Array 字段,该字段将容纳 String 值。
我需要模型中的 Mongoid 的 范围 来检索此 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 怎么会只是说元素必须等于给定值???。
关于如何编写这个非常简单的作用域的任何线索???。
问候!!!。提前致谢。
最佳答案
你的事情过于复杂了。如果一个字段包含一个数组,那么您可以搜索它,就好像它不是一个数组一样。例如,如果您在文档中有此内容:
{ some_array: [ 'where', 'is', 'pancakes', 'house?' ] }
然后你做这样的查询:
where(:some_array => 'pancakes')
您会找到该文档。你不需要 $elemMatch
或任何复杂的东西;你可以假装数组是一个简单的查询,就像你有:
scope :some_scope, ->(value) { where(:some_array => value) }
您只需进入$elemMatch
如果你想对数组的每个元素应用多个条件,像 $elemMatch
这样的事情文档:
results: { $elemMatch: { $gte: 80, $lt: 85 } }
// ^^^^^^^array ^^^^^^^^^^^^^^^^^^^^^multiple conditions
别难过,当前的 MongoDB 文档对这些东西并不十分清楚(或者至少我找不到明确的解释)。
关于ruby-on-rails - Mongoid 范围检查数组字段是否包含值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26303715/