Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k points)

I want to print the value for this JSON document in the mongo shell. Like a simple console output, without creating a new collection or document.

enter image description here

Thanks in advance

1 Answer

0 votes
by (108k points)
edited by

For printing the value in MongoDB Shell you have to work with forEach() function. Let us discuss this with an example:

Let's create a collection titled ‘printDocuementValueDemo’ and inside the collection, let's add documents:

> db.printDocuementValueDemo.insertOne({"InstructorName":"John Smith"});

{

   "acknowledged" : true,

   "insertedId" : ObjectId("5cd6804f7924bb85b3f48950")

}

> db.printDocuementValueDemo.insertOne({"InstructorName":"Sam Williams"});

{

   "acknowledged" : true,

   "insertedId" : ObjectId("5cd680577924bb85b3f48951")

}

> db.printDocuementValueDemo.insertOne({"InstructorName":"David Miller"});

{

   "acknowledged" : true,

   "insertedId" : ObjectId("5cd680637924bb85b3f48952")

}

After that read your documents:

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

The output would be as follows:

{

   "_id" : ObjectId("5cd6804f7924bb85b3f48950"),

   "InstructorName" : "John Smith"

}

{

   "_id" : ObjectId("5cd680577924bb85b3f48951"),

   "InstructorName" : "Sam Williams"

}

{

   "_id" : ObjectId("5cd680637924bb85b3f48952"),

   "InstructorName" : "David Miller"

}

Then for printing, the document refers to the following syntax:

> db.printDocuementValueDemo.find(

   { _id : ObjectId("5cd680577924bb85b3f48951") },

   {InstructorName: 1, _id:0}

).forEach(function(myDocument) {

   print(myDocument.InstructorName);

});

The output for the above code will be:

Sam Williams

Do you wish to learn MongoDB? Grab the chance through this MongoDB course.

Also, have a look at this professional Full Stack Developer Training, designed to enhance your skills in the field.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jan 29, 2020 in Web Technology by ashely (50.2k points)
0 votes
1 answer
0 votes
1 answer
asked Oct 18, 2019 in Web Technology by Sammy (47.6k points)

Browse Categories

...