For this, work with the concept of forEach(). Let us first create a collection with 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")
}Following is the query to display all documents from a collection with the help of find() method −
> db.printDocuementValueDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd6804f7924bb85b3f48950"),
"InstructorName" : "John Smith"
}
{
"_id" : ObjectId("5cd680577924bb85b3f48951"),
"InstructorName" : "Sam Williams"
}
{
"_id" : ObjectId("5cd680637924bb85b3f48952"),
"InstructorName" : "David Miller"
}Following is the query to print document value in MongoDB shell −
> db.printDocuementValueDemo.find(
{ _id : ObjectId("5cd680577924bb85b3f48951") },
{InstructorName: 1, _id:0}
).forEach(function(myDocument) {
print(myDocument.InstructorName);
});This will produce the following output −
Sam Williams