How to read a specific key-value pair from a MongoDB collection?


You can use dot(.) notation to read a specific key-value pair from MongoDB collection. Let us first create a collection with documents −

> db.readSpecificKeyValueDemo.insertOne(
...    {
...       "_id": 100,
...       "StudentDetails":
...       {
...          "StudentFirstName" : "David",
...          "StudentLastName" :"Miller",
...          "StudentAge":23,
...          "StudentCountryName":"US"
...       }
...    }
... );
{ "acknowledged" : true, "insertedId" : 100 }

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

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

This will produce the following output −

{
   "_id" : 100,
   "StudentDetails" : {
      "StudentFirstName" : "David",
      "StudentLastName" : "Miller",
      "StudentAge" : 23,
      "StudentCountryName" : "US"
   }
}

Following is the query to read a specific key-value pair from a MongoDB collection −

> db.readSpecificKeyValueDemo.find({},{"StudentDetails.StudentCountryName":1}).pretty();

This will produce the following output −

{ "_id" : 100, "StudentDetails" : { "StudentCountryName" : "US" } }

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

684 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements