数组字段的Mongoid查询 [英] Mongoid query for array field
问题描述
我在Mongoid中有一个type
Array
的category
字段.
I have a category
field of type
Array
in Mongoid.
例如类别:["val1","val2","val3"]
Ex. category: ["val1","val2","val3"]
现在我想用`category:["val1","val2"]查询该模型,以便它返回我的
Now I want to query this Model with `category: ["val1","val2"] such that it returns me the merge of
Model.where(类别:"val1")和Model.where(类别:"val2")
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.
我也尝试过Model.all_of({category: "val1"},{category: "val2"}).all
,但是没有用.
I also tried Model.all_of({category: "val1"},{category: "val2"}).all
but that is not working.
我应该怎么做?
推荐答案
在蒙古语中,有一个'$ in'运算符.因此,您可以这样做:
In mongoid, there is '$in' operator. So you can do this :
Model.where(category: { '$in': ['val1', 'val2'] })
这篇关于数组字段的Mongoid查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!