使用MongoDB通过特定值查找具有字段名的文档?
要根据特定值通过字段名查找文档,您可以使用 $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" } } }
广告