查询值为Null或不存在的字段

您所在的位置:网站首页 collections排序的字段为null 查询值为Null或不存在的字段

查询值为Null或不存在的字段

2024-07-10 14:20| 来源: 网络整理| 查看: 265

查询值为Null或不存在的字段¶

本页内容

相等过滤器 类型筛查 存在性筛查

MongoDB中不同的运算符对待 null 值不一样.

本页中的示例使用 mongo shell中的 db.collection.find() 方法.在:program:mongo shell中运行如下命令以向示例中涉及到的 users 集合填入数据:

db.users.insert( [ { "_id" : 900, "name" : null }, { "_id" : 901 } ] ) 相等过滤器¶

The { name : null } query matches documents that either contain the name field whose value is null or that do not contain the name field.

给出如下查询:

db.users.find( { name: null } )

该查询返回这两个文档:

{ "_id" : 900, "name" : null } { "_id" : 901 }

如果该查询使用了 sparse 索引,不管怎样,那么该查询将仅仅匹配 null 值,而不匹配不存在的字段.

在 2.6 版更改: 如果使用稀疏索引会导致一个不完整的结果,那么,除非 hint() 显示地指定了该索引,否则MongoDB将不会使用这个索引.更多信息请参见 稀疏索引.

类型筛查¶

{ name : { $type: 10 } } 查询 仅仅 匹配那些包含值是 null 的 name 字段的文档,亦即 条目 字段的值是BSON类型中的 Null (即 10 ):

db.users.find( { name : { $type: 10 } } )

该查询只返回文 条目 字段是 null 值的文档:

{ "_id" : 900, "name" : null } 存在性筛查¶

The { name : { $exists: false } } query matches documents that do not contain the item field:

db.users.find( { name : { $exists: false } } )

该查询只返回那些 没有 包含 条目 字段的文档:

{ "_id" : 901 }

参见

The reference documentation for the $type and $exists operators.



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3