如何查询MongoDB中字段为空或未设置的记录?
让我们解决两种情况-
情况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