要基于真值或假值进行查找,请在find()中使用$exists。对于同一任务,您还需要点符号。
首先让我们创建一个包含文档的集合-
> db.demo367.insertOne( ... { "Id" : "102", ... "details" : [ { "Name" : "David"}, ... { "Age" : 23, "CountryName" : "UK"} ], ... "isMarried" : false } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e57e0b62ae06a1609a00ae8") } > db.demo367.insertOne( ... { "Id" : "101", ... "details" : [ { "Name" : "Chris", "Subject" : [ "MySQL" ] }, ... { "Age" : 21, "CountryName" : "US"} ], ... "isMarried" : true } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e57e0be2ae06a1609a00ae9") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo367.find();
这将产生以下输出-
{ "_id" : ObjectId("5e57e0b62ae06a1609a00ae8"), "Id" : "102", "details" : [ { "Name" : "David" }, { "Age" : 23, "CountryName" : "UK" } ], "isMarried" : false } { "_id" : ObjectId("5e57e0be2ae06a1609a00ae9"), "Id" : "101", "details" : [ { "Name" : "Chris", "Subject" : [ "MySQL" ] }, { "Age" : 21, "CountryName" : "US" } ], "isMarried" : true }
以下是通过与$exists进行检查以基于真假值查找的查询-
> db.demo367.find({"details.Subject": { $exists: false}});
这将产生以下输出-
{ "_id" : ObjectId("5e57e0b62ae06a1609a00ae8"), "Id" : "102", "details" : [ { "Name" : "David" }, { "Age" : 23, "CountryName" : "UK" } ], "isMarried" : false }