MongoDB查询布尔字段为“ not true”

您可以为此使用$ne(不等于)运算符。语法如下-

db.yourCollectionName.find({yourFieldName: {$ne: true}}).pretty();

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

> db.queryForBooleanFieldsDemo.insertOne({"EmployeeName":"Larry","EmployeeAge":24,"isOldEmployee":true});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8b7f7680f10143d8431e13")
}
> db.queryForBooleanFieldsDemo.insertOne({"EmployeeName":"Mike","EmployeeAge":20,"isOldEmployee":false});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8b7f8680f10143d8431e14")
}
> db.queryForBooleanFieldsDemo.insertOne({"EmployeeName":"Sam","EmployeeAge":23,"isOldEmployee":false});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8b7f9380f10143d8431e15")
}
> db.queryForBooleanFieldsDemo.insertOne({"EmployeeName":"David","EmployeeAge":25,"isOldEmployee":true});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8b7fa280f10143d8431e16")
}
> db.queryForBooleanFieldsDemo.insertOne({"EmployeeName":"Carol","EmployeeAge":27,"isOldEmployee":true});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8b7fae80f10143d8431e17")
}

find()method的帮助下显示集合中的所有文档。查询如下-

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

以下是输出-

{
   "_id" : ObjectId("5c8b7f7680f10143d8431e13"),
   "EmployeeName" : "Larry",
   "EmployeeAge" : 24,
   "isOldEmployee" : true
}
{
   "_id" : ObjectId("5c8b7f8680f10143d8431e14"),
   "EmployeeName" : "Mike",
   "EmployeeAge" : 20,
   "isOldEmployee" : false
}
{
   "_id" : ObjectId("5c8b7f9380f10143d8431e15"),
   "EmployeeName" : "Sam",
   "EmployeeAge" : 23,
   "isOldEmployee" : false
}
{
   "_id" : ObjectId("5c8b7fa280f10143d8431e16"),
   "EmployeeName" : "David",
   "EmployeeAge" : 25,
   "isOldEmployee" : true
}
{
   "_id" : ObjectId("5c8b7fae80f10143d8431e17"),
   "EmployeeName" : "Carol",
   "EmployeeAge" : 27,
   "isOldEmployee" : true
}

这是布尔字段查询为“不正确”-

> db.queryForBooleanFieldsDemo.find({isOldEmployee: {$ne: true}}).pretty();

以下是输出-

{
   "_id" : ObjectId("5c8b7f8680f10143d8431e14"),
   "EmployeeName" : "Mike",
   "EmployeeAge" : 20,
   "isOldEmployee" : false
}
{
   "_id" : ObjectId("5c8b7f9380f10143d8431e15"),
   "EmployeeName" : "Sam",
   "EmployeeAge" : 23,
   "isOldEmployee" : false
}