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

MongoDBDatabaseBig Data Analytics

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" } }
raja
Published on 30-Apr-2019 13:53:20
Advertisements