How to retrieve a value from MongoDB by its key name?


To retrieve a value from MongoDB by its key name, use the following syntax −

db.yourCollectionName.find({},{"yourFieldName":1}).pretty();

To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.retrieveValueFromAKeyDemo.insertOne({"CustomerName":"Larry","CustomerAge":21,"CustomerCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9163b5a56efcc0f9e69048")
}
> db.retrieveValueFromAKeyDemo.insertOne({"CustomerName":"Chris","CustomerAge":24,"CustomerCountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9163c4a56efcc0f9e69049")
}
> db.retrieveValueFromAKeyDemo.insertOne({"CustomerName":"Mike","CustomerAge":26,"CustomerCountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9163d3a56efcc0f9e6904a")
}

Display all documents from a collection with the help of find() method. The query is as follows −

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

The following is the output −

{
   "_id" : ObjectId("5c9163b5a56efcc0f9e69048"),
   "CustomerName" : "Larry",
   "CustomerAge" : 21,
   "CustomerCountryName" : "US"
}
{
   "_id" : ObjectId("5c9163c4a56efcc0f9e69049"),
   "CustomerName" : "Chris",
   "CustomerAge" : 24,
   "CustomerCountryName" : "AUS"
}
{
   "_id" : ObjectId("5c9163d3a56efcc0f9e6904a"),
   "CustomerName" : "Mike",
   "CustomerAge" : 26,
   "CustomerCountryName" : "UK"
}

Here is the query to retrieve a value from MongoDB by its key name i.e. we have considered the key ‘CustomerCountryName’ −

> db.retrieveValueFromAKeyDemo.find({},{"CustomerCountryName":1}).pretty();

The following is the output:

{
   "_id" : ObjectId("5c9163b5a56efcc0f9e69048"),
   "CustomerCountryName" : "US"
}
{
   "_id" : ObjectId("5c9163c4a56efcc0f9e69049"),
   "CustomerCountryName" : "AUS"
}
{
   "_id" : ObjectId("5c9163d3a56efcc0f9e6904a"),
   "CustomerCountryName" : "UK"
}

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements