gpt4 book ai didi

mongodb - Mongoid 按值或默认值查询

转载 作者:可可西里 更新时间:2023-11-01 10:00:58 33 4
gpt4 key购买 nike

我刚刚用 bool 字段更新了我的一个模型。我已将该字段的默认值设置为 true。我如何查询此字段,以便我获取所有此字段设置为 true 或没有此字段(默认值)的文档。

最佳答案

要查找没有特定键的文档,您需要使用 $exists :

$exists
Syntax: { field: { $exists: <boolean> } }

$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.

所以存在性检查看起来像:

Model.where(:field.exists => false)
Model.where(:field => { :$exists => false })

注意第一个 :field.exists表单在发送到 MongoDB 之前成为第二个表单;我提到这个是因为你将无法使用 :field在查询的其他地方不使用 $and$or组合子句::field.exists扩展会导致查询哈希中的键相互覆盖。在这里您不会遇到这个问题,但提醒也无妨。

正在寻找 true很简单:

Model.where(:field => true)

你想要任何一个,所以将它们与 $or 结合起来:

Model.where(:$or => [
{ :field.exists => false },
{ :field => true }
])

如果:field可能在那里,但有一个 null value 那么你可以使用 { :field => nil }匹配文件 :fieldnull 根本不存在:

Model.where(:$or => [
{ :field => null },
{ :field => true }
])
# or
Model.where(:field.in => [ null, true ]) # This is probably the one you want

还有 { :field => { :$type => 10 } }如果您正在寻找明确存在的东西 null .现在可能是快速回顾一下 MongoDB FAQ 的好时机:

How do I query for fields that contain null values?

关于mongodb - Mongoid 按值或默认值查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21143493/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com