How to return only value of a field in MongoDB?


In order to return only value of a field in MongoDB, you need to write a query and use forEach loop. Let us first create a collection with documents

> db.returnOnlyValueOfFieldDemo.insertOne({"ClientName":"Larry"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ea537d628fa4220163b6e")
}
> db.returnOnlyValueOfFieldDemo.insertOne({"ClientName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ea53bd628fa4220163b6f")
}
> db.returnOnlyValueOfFieldDemo.insertOne({"ClientName":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ea541d628fa4220163b70")
}
> db.returnOnlyValueOfFieldDemo.insertOne({"ClientName":"Ramit"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ea549d628fa4220163b71")
}

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

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

This will produce the following output

{ "_id" : ObjectId("5c9ea537d628fa4220163b6e"), "ClientName" : "Larry" }
{ "_id" : ObjectId("5c9ea53bd628fa4220163b6f"), "ClientName" : "Chris" }
{ "_id" : ObjectId("5c9ea541d628fa4220163b70"), "ClientName" : "Robert" }
{ "_id" : ObjectId("5c9ea549d628fa4220163b71"), "ClientName" : "Ramit" }

Following is the query to return only value of a field in MongoDB

> var output = []
> db.returnOnlyValueOfFieldDemo.find().forEach(function(document) {output.push(document.ClientName) })

In order to get value of a field in MongoDB, you need to write variable name output at the Mongo shell (as we know the value is stored in output array). Following is the query

> output

This will produce the following output

[ "Larry", "Chris", "Robert", "Ramit" ]

Updated on: 30-Jul-2019

708 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements