您可以将$eq和$ne运算符用于布尔值。首先让我们创建一个包含文档的集合-
> db.booleanQueryDemo.insertOne({"UserName":"John","UserAge":23,"isMarried":true}); { "acknowledged" : true, "insertedId" : ObjectId("5cc815c08f9e6ff3eb0ce44a") } > db.booleanQueryDemo.insertOne({"UserName":"Chris","UserAge":21,"isMarried":false}); { "acknowledged" : true, "insertedId" : ObjectId("5cc815d08f9e6ff3eb0ce44b") } > db.booleanQueryDemo.insertOne({"UserName":"Robert","UserAge":24,"isMarried":false}); { "acknowledged" : true, "insertedId" : ObjectId("5cc815dc8f9e6ff3eb0ce44c") } > db.booleanQueryDemo.insertOne({"UserName":"David","UserAge":26,"isMarried":true}); { "acknowledged" : true, "insertedId" : ObjectId("5cc815ed8f9e6ff3eb0ce44d") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.booleanQueryDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cc815c08f9e6ff3eb0ce44a"), "UserName" : "John", "UserAge" : 23, "isMarried" : true } { "_id" : ObjectId("5cc815d08f9e6ff3eb0ce44b"), "UserName" : "Chris", "UserAge" : 21, "isMarried" : false } { "_id" : ObjectId("5cc815dc8f9e6ff3eb0ce44c"), "UserName" : "Robert", "UserAge" : 24, "isMarried" : false } { "_id" : ObjectId("5cc815ed8f9e6ff3eb0ce44d"), "UserName" : "David", "UserAge" : 26, "isMarried" : true }
情况1-当值等于false时。
以下是布尔值的查询-
> db.booleanQueryDemo.find({isMarried: {$eq: false}}).pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cc815d08f9e6ff3eb0ce44b"), "UserName" : "Chris", "UserAge" : 21, "isMarried" : false } { "_id" : ObjectId("5cc815dc8f9e6ff3eb0ce44c"), "UserName" : "Robert", "UserAge" : 24, "isMarried" : false }
情况2-当值等于true时。
以下是查询-
> db.booleanQueryDemo.find({isMarried: {$ne: false}}).pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cc815c08f9e6ff3eb0ce44a"), "UserName" : "John", "UserAge" : 23, "isMarried" : true } { "_id" : ObjectId("5cc815ed8f9e6ff3eb0ce44d"), "UserName" : "David", "UserAge" : 26, "isMarried" : true }