要通过具有特定值的字段名称查找文档,可以使用$exists运算符。让我们创建包含文档的集合
> db.findByFieldName.insertOne( { "Client":{ "ClientDetails":{ "ClientName":"Larry", "ClientAge":29 }, "ClientProjectDetails":{ "ProjectName":"Online Book Store", "TeamSize":10, "TechnologyUsed":"Spring Boot" } } } ); { "acknowledged" : true, "insertedId" : ObjectId("5c9e93b2d628fa4220163b64") } > db.findByFieldName.insertOne({ ... " Client":{ ... " ClientDetails":{ ... " ClientName":"Chris", ... " ClientAge":27 ... }, ... "ClientEducationDetails":{ ... " isEducated":true, ... "CollegeName":"M.I.T." ... ... } ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5c9e9421d628fa4220163b65") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.findByFieldName.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9e93b2d628fa4220163b64"), "Client" : { "ClientDetails" : { "ClientName" : "Larry", "ClientAge" : 29 }, "ClientProjectDetails" : { "ProjectName" : "Online Book Store", "TeamSize" : 10, "TechnologyUsed" : "Spring Boot" } } } { "_id" : ObjectId("5c9e9421d628fa4220163b65"), "Client" : { "ClientDetails" : { "ClientName" : "Chris", "ClientAge" : 27 }, "ClientEducationDetails" : { "isEducated" : true, "CollegeName" : "M.I.T." } } }
以下是按字段名称查找文档的查询
> db.findByFieldName.find({"Client.ClientProjectDetails":{$exists: true}}).pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9e93b2d628fa4220163b64"), "Client" : { "ClientDetails" : { "ClientName" : "Larry", "ClientAge" : 29 }, "ClientProjectDetails" : { "ProjectName" : "Online Book Store", "TeamSize" : 10, "TechnologyUsed" : "Spring Boot" } } }