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.