首页 > 解决方案 > 为什么mongodb会找到这个文档($ne: null for array)

问题描述

数据:

db.inventory.insertMany([
       { _id: 1, item: null },
       { _id: 2 },
       { _id: 3, item: 3 },
       { _id: 4 items: [1, 2, 3] },
       { _id: 5, items: [] }
    ])

查询一:

db.inventory.find({ 'item': {$ne: null} })

结果1:

{ _id: 3, item: 3 }

查询 2:

db.inventory.find({ 'items.0': {$ne: null} })

结果 2:

{ _id: 3, items: [1, 2, 3] },
{ _id: 4, items: [] }

为什么 mongoDB 会找到这个文档:{ _id: 4, items: [] }?这是一个错误吗?

标签: mongodb

解决方案


Use $exists: true instead of $ne: null.

$ne docs explain:

$ne selects the documents where the value of the field is not equal to the specified value. This includes documents that do not contain the field.


推荐阅读