Find the document by field name with a specific value in MongoDB?



To find the document by field name with a specific value, you can use $exists operator. Let us create a collection with documents

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

Following is the query to display all documents from a collection with the help of find() method

> db.findByFieldName.find().pretty();

This will produce the following output

{    "_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."       }    } }

Following is the query to find the document by field name

> db.findByFieldName.find({"Client.ClientProjectDetails":{$exists: true}}).pretty();

This will produce the following output

{    "_id" : ObjectId("5c9e93b2d628fa4220163b64"),    "Client" : {       "ClientDetails" : {          "ClientName" : "Larry",          "ClientAge" : 29       },       "ClientProjectDetails" : {          "ProjectName" : "Online Book Store",          "TeamSize" : 10,          "TechnologyUsed" : "Spring Boot"       }    } }
Updated on: 2019-07-30T22:30:25+05:30

634 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements