17

I have a category field of type Array in Mongoid.

Ex. category: ["val1","val2","val3"]

Now I want to query this Model with `category: ["val1","val2"] such that it returns me the merge of

Model.where(category: "val1") and Model.where(category: "val2")

I can do it individually for each element of the array but that will be slow I guess because for every individual element it will search all the documents.

I also tried Model.all_of({category: "val1"},{category: "val2"}).all but that is not working.

How should I do this?

4

4 回答 4

35

在 mongoid 中,有 '$in' 运算符。所以你可以这样做:

Model.where(category: { '$in': ['val1', 'val2'] })
于 2013-11-08T21:15:11.817 回答
11

您可以使用Criteria all_in使其更简单:

Model.all_in(category: ['val1','val2'])
于 2014-10-29T15:33:40.843 回答
7

这有效

Model.where(:category.in => ['val1','val2'])

来自Mongo 文档

于 2016-02-19T20:38:11.053 回答
1

或另一种变体:

Model.in(category: ['val1','val2'])
于 2020-01-11T03:37:04.917 回答