在Mongodb集合中,并没有要求每一个文档具有相同的结构和字段类型。而随着业务的扩展,新插入的文档中,难免会增加新的字段。同样某些字段也可能出现空值null的情况。本文结合mongodb官方文档,整理了mongodb空值null和缺失字段的查询。
在库存表当中有两条数据,其中_id为1的文档, 存在item字段,但该字段的值是空值。而_id为2的文档,不包含字段item.
db.inventory.insertMany([
{_id: 1, item: null},
{_id: 2}
])
等值查询
使用{item: null}查询集合inventory, 返回字段item为null的文档和不存在字段item的文档
db.inventory.find({item: null})
/* 1 */
{
"_id" : 1,
"item" : null
},
/* 2 */
{
"_id" : 2
}
类型检查
使用{$type: null},查询item字段为null类型的的文档。
db.inventory.find({item: {$type: 10}})
db.inventory.find({item: {$type: "null"}})
{
"_id" : 1,
"item" : null
}
存在检查
使用{$exists: false}, 查询出没有字段item的文档
db.inventory.find({item: {$exists: false}})
{
"_id" : 2
}
使用{$exists: true}, 查询出存在字段item的文档。无论该字段值是哪种类型,都会被查出来。
db.inventory.find({item: {$exists: true}})
{
"_id" : 1,
"item" : null
}