如何在 MongoDB 中查询字段为 null 或未设置的记录?


下面两种情况的使用指南 −

情况 1 − 当字段存在且设置为 null 时的语法如下。

db.yourCollectionName.count({yourFieldName: null});

情况 1 − 当字段不存在且未设置时的语法如下。

db.yourCollectionName.count({yourFieldName: {$exists: false}});

为理解上述语法,让我们使用文档创建一个集合。通过文档创建集合的查询如下 −

> db.fieldIsNullOrNotSetDemo.insertOne({"EmployeeName":"Larry","EmployeeAge":null,"EmployeeSalary":18500});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a995c6cea1f28b7aa07fe")
}
> db.fieldIsNullOrNotSetDemo.insertOne({"EmployeeName":"Bob","EmployeeAge":21,"EmployeeSalary":23500});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a99836cea1f28b7aa07ff")
}

> db.fieldIsNullOrNotSetDemo.insertOne({"EmployeeName":"Carol","EmployeeSalary":45500});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a999b6cea1f28b7aa0800")
}
> db.fieldIsNullOrNotSetDemo.insertOne({"EmployeeName":"Mike","EmployeeAge":null,"EmployeeSalary":45500});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a99bb6cea1f28b7aa0801")
}
> db.fieldIsNullOrNotSetDemo.insertOne({"EmployeeName":"Ramit","EmployeeSalary":85500});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a99d76cea1f28b7aa0802")
}

借助 find() 方法显示来自集合的所有文档。查询如下 −

> db.fieldIsNullOrNotSetDemo.find().pretty();

输出如下 −

{
   "_id" : ObjectId("5c8a995c6cea1f28b7aa07fe"),
   "EmployeeName" : "Larry",
   "EmployeeAge" : null,
   "EmployeeSalary" : 18500
}
{
   "_id" : ObjectId("5c8a99836cea1f28b7aa07ff"),
   "EmployeeName" : "Bob",
   "EmployeeAge" : 21,
   "EmployeeSalary" : 23500
}
{
   "_id" : ObjectId("5c8a999b6cea1f28b7aa0800"),
   "EmployeeName" : "Carol",
   "EmployeeSalary" : 45500
}
{
   "_id" : ObjectId("5c8a99bb6cea1f28b7aa0801"),
   "EmployeeName" : "Mike",
   "EmployeeAge" : null,
   "EmployeeSalary" : 45500
}
{
   "_id" : ObjectId("5c8a99d76cea1f28b7aa0802"),
   "EmployeeName" : "Ramit",
   "EmployeeSalary" : 85500
}

情况 1

字段 EmployeeAge 存在且设置为 null。

查询如下 −

> db.fieldIsNullOrNotSetDemo.count({EmployeeAge: null});

输出如下 −

4

情况 2

字段 'EmployeeAge' 不存在且未设置。查询如下 −

> db.fieldIsNullOrNotSetDemo.count({EmployeeAge: {$exists: false}});

输出如下 −

2

更新日期: 30-Jul-2019

691 次浏览

开启你 职业生涯

通过完成课程获得认证

开始
广告