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() 方法显示所有文档。该查询如下所示 −

> 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
}

以下是布尔字段为 “not 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
}

更新于: 30-07-2019

836 次浏览

开始你的 职业生涯

完成课程获得认证

开始学习
广告