插入測試數據
db.inventory.insertMany([ { _id: 1, item: null }, { _id: 2 } ])
后面的栗子都會用到這里的測試數據
查詢匹配包含值為 null 的 item 字段或不包含 item 字段的文檔
> db.inventory.find( { item: null } ) { "_id" : 1, "item" : null } { "_id" : 2 }
如果我想單獨的把字段值有 null 的文檔找出來或者把沒有 item 字段的文檔找出來呢?
只查詢包含值為 null 的 item 字段
> db.inventory.find( { item : { $type: 10 } } ) { "_id" : 1, "item" : null }
還記得嗎,在 BSON 數據類型里面,null 的序號是 10
只查詢不包含 item 字段的文檔
> db.inventory.find({ item :{ $exists : false } }) { "_id" : 2 }
只查詢包含 item 字段的文檔
> db.inventory.find({ item :{ $exists : true } }) { "_id" : 1, "item" : null }
記住如果想查詢不包含/包含某個字段的文檔,是用 $exists 操作符哦