MongoDB 查找所有值为未定义的内容

Gha*_*han 6 mongodb mongodb-query

您好,我通过在 NoSQLBooster IDE 中编写一些普通的 javascript 意外地将 mongodb 中的一些记录更新为未定义的值。问题是记录存在,但是当我将 $exists 运行为 true 时,它​​显示 Robo3T 中的记录,但不显示 NoSQLBooster 中的记录。然而,当我运行 email is equal to undefined 时,它不会返回任何记录,但记录存在。这是示例查询和结果屏幕截图

 db.customer.find({source:'some value',"email":{$exists: true}})
   .projection({})
   .sort({_id:-1})
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我如何查询和更正这些记录。谢谢

Joh*_*yHK 17

您可以使用运算符查询文档 where emailis :undefined$type

db.customer.find({source: 'some value', email: {$type: 'undefined'}})
Run Code Online (Sandbox Code Playgroud)

请注意,未定义的类型在文档中被列为已弃用,但目前仍然有效。

查询email: null也将返回这些文档,但这也将包括email丢失或设置为 的文档null。因此,您需要使用另外两个术语进一步限定查询以排除这些术语:

db.customer.find({$and: [
    {source: 'some value'},
    {email: null}, 
    {email: {$not: {$type: 'null'}}}, 
    {email: {$exists: true}}]})
Run Code Online (Sandbox Code Playgroud)