通过大小在范围内的数组进行Mongoid查询

时间:2015-03-08 23:17:14

标签: mongoid

如何通过范围大小的数组进行查询?

文件:

Foo { foo_array: [{name: "item_1"},{name: "item_2}] }
Foo { foo_array: [{name: "item_1"}] }
Foo { foo_array: [{name: "item_1"},{name: "item_2},{name: "item_3}] }

例如,我试图得到: foo_array字段有2到3个项目的Foo对象。

类似的东西:

Foo.where(:foo_array.with_size => [2,3])

1 个答案:

答案 0 :(得分:3)

您可以按索引查询数组,然后检查所需索引处的元素是否存在。例如:

Foo.where(
  # something at index 1 means that the size is at least two
  'foo_array.1' => { :$exists => true },
  # nothing at index 3 means that the size is at most three
  'foo_array.3' => { :$exists => false }
)