【问题标题】:Mongoid query by value or default valueMongoid 按值或默认值查询
【发布时间】:2014-02-04 06:43:42
【问题描述】:

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

【问题讨论】:

    标签: mongodb mongoid


    【解决方案1】:

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

    $exists
    语法{ field: { $exists: <boolean> } }

    $exists 如果<boolean> 为真,则选择包含该字段的文档。如果<boolean> 为假,则查询只返回不包含该字段的文档。 $exists 确实匹配包含存储 null 值的字段的文档。

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

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

    请注意,第一个 :field.exists 表单在发送到 MongoDB 之前会变成第二个表单;我提到这一点是因为如果不使用$and$or 组合子句,您将无法在查询的其他地方使用:field:field.exists 扩展可能导致查询中的键哈希覆盖彼此。你不会在这里遇到这个问题,但提醒不会有什么坏处。

    寻找true 很容易:

    Model.where(:field => true)
    

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

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

    如果:field 可能存在但有null 值,那么您可以使用{ :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 常见问题解答的好时机:

    How do I query for fields that contain null values?

    【讨论】:

      猜你喜欢
      • 2020-09-02
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 2019-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-17
      相关资源
      最近更新 更多