按值或默认值查询 [英] Mongoid query by value or default value
问题描述
我刚刚用布尔值字段更新了我的一个模型.我已将字段的默认值设置为true.如何以一种方式查询此字段,以使所有将该字段设置为true或没有此字段(默认值)的文档.
I've just updated one of my models with a boolean field. I've set a default value for the field to true. How can I query for this field in such a way that I get all documents with this field set to true or doesn't have this field (default value).
推荐答案
To find documents that don't have a particular key, you want to use $exists
:
$存在
语法:{ field: { $exists: <boolean> } }
$exists
Syntax:{ field: { $exists: <boolean> } }
$exists
选择包含该字段的文档.如果<boolean>
为false,则查询仅返回不包含该字段的文档. $exists
与包含包含null
值的字段的文档匹配.
$exists
selects the documents that contain the field if <boolean>
is true. If <boolean>
is false, the query only returns the documents that do not contain the field. $exists
does match documents that contain the field that stores the null
value.
因此,存在检查将如下所示:
So the existence check would look like:
Model.where(:field.exists => false)
Model.where(:field => { :$exists => false })
请注意,第一个:field.exists
表单在发送到MongoDB之前变成了第二个表单;我之所以这样说是因为,如果不使用$and
或$or
来组合这些子句,就无法在查询的其他地方使用:field
::field.exists
扩展会导致查询中的键哈希相互覆盖.您不会在这里遇到这个问题,但提醒不会受到伤害.
Note that the first :field.exists
form becomes the second form before it gets sent to MongoDB; I mention this because you won't be able to use :field
elsewhere in the query without using $and
or $or
to combine the clauses: the :field.exists
expansion can lead to keys in the query Hash overwriting each other. You won't have this problem here but a reminder can't hurt.
查找true
很容易:
Model.where(:field => true)
您想要其中一个,因此可以将它们与 $or
结合使用:
You want either one so combine them with $or
:
Model.where(:$or => [
{ :field.exists => false },
{ :field => true }
])
如果:field
可能存在但具有null
值,则可以使用{ :field => nil }
匹配:field
为null
或根本不存在的文档:>
If :field
might be there but have a null
value then you could use { :field => nil }
to match documents where :field
is null
or not there at all:
Model.where(:$or => [
{ :field => null },
{ :field => true }
])
# or
Model.where(:field.in => [ null, true ]) # This is probably the one you want
如果您正在查找和明确显示的null
内容,也有{ :field => { :$type => 10 } }
.现在可能是快速回顾MongoDB常见问题的好时机:
There's also { :field => { :$type => 10 } }
if you're looking for things that are there and explicitly null
. Now might be a good time for a quick review of the MongoDB FAQ:
这篇关于按值或默认值查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!