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

MongoDBDatabaseBig Data Analytics

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"
      }
   }
}
raja
Published on 12-Apr-2019 11:42:42
Advertisements