MongoDB null

MongoDB null

MongoDB 中,我们使用 find 查询记录时,如果要查询不包含某个键的文档,我们可以使用 null 来查询,当然 null 也可以匹配元素的值为 null 的记录。

MongoDB null详解

语法

db_name.collection_name.find({field:null})

参数

参数 描述
db_name 数据库名
collection_name 集合名
field 要查询的字段

说明

查询 field 字段的值为 null 或者字段 field 字段不存在的记录。

案例

我们首先,使用 mongo 命令,连接上数据库,具体命令如下:

mongo

如下图所示:

96_mongodb null.png

现在,我们使用 use 命令,切换到 haicoder 数据库,具体命令如下:

use haicoder

现在,我们使用 insertMany 插入三条记录,具体命令如下:

db.haicoder.insertMany([{"name":"haicoder", "url":"haicoder.net"}, {"name":"mhaicoder", "url":"m.haicoder.net"}, {"name":null, "url":"www.haicoder.net"}])

执行完毕后,此时,如下图所示:

97_mongodb null.png

我们看到,此时提示我们成功插入了三条记录,现在,我们使用 find 进行查询,查询 name 字段为 null 的记录,具体命令如下:

db.haicoder.find({"name":null})

执行完毕后,此时,如下图所示:

98_mongodb null.png

我们看到,此时我们查询了 name 字段为 null 的记录,现在我们再次查询 age 不存在的记录,具体命令如下:

db.haicoder.find({"age":null}, {_id:0})

执行完毕后,此时,如下图所示:

99_mongodb null.png

我们看到,我们查询了 age 字段不存在的所有记录。

MongoDB null总结

在 MongoDB 中,我们使用 find 查询记录时,如果要查询不包含某个键的文档,我们可以使用 null 来查询,当然 null 也可以匹配元素的值为 null 的记录。