How to print document value in MongoDB shell?

To print specific document values in MongoDB shell, use the forEach() method combined with the print() function. This allows you to extract and display individual field values from query results.

Syntax

db.collection.find(query, projection).forEach(function(document) {
    print(document.fieldName);
});

Sample Data

db.printDocumentValueDemo.insertMany([
    {"InstructorName": "John Smith"},
    {"InstructorName": "Sam Williams"},
    {"InstructorName": "David Miller"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cd6804f7924bb85b3f48950"),
        ObjectId("5cd680577924bb85b3f48951"),
        ObjectId("5cd680637924bb85b3f48952")
    ]
}

Display All Documents

db.printDocumentValueDemo.find().pretty();
{
    "_id": ObjectId("5cd6804f7924bb85b3f48950"),
    "InstructorName": "John Smith"
}
{
    "_id": ObjectId("5cd680577924bb85b3f48951"),
    "InstructorName": "Sam Williams"
}
{
    "_id": ObjectId("5cd680637924bb85b3f48952"),
    "InstructorName": "David Miller"
}

Example: Print Specific Field Value

Print only the InstructorName for a specific document ?

db.printDocumentValueDemo.find(
    { _id: ObjectId("5cd680577924bb85b3f48951") },
    { InstructorName: 1, _id: 0 }
).forEach(function(myDocument) {
    print(myDocument.InstructorName);
});
Sam Williams

Example: Print All Names

Print all instructor names using forEach() ?

db.printDocumentValueDemo.find(
    {},
    { InstructorName: 1, _id: 0 }
).forEach(function(doc) {
    print(doc.InstructorName);
});
John Smith
Sam Williams
David Miller

Key Points

  • Use projection to include only required fields and exclude _id if not needed.
  • The forEach() method iterates through each document returned by find().
  • Access field values using dot notation: document.fieldName.

Conclusion

The forEach() method with print() is ideal for extracting and displaying specific field values from MongoDB documents. Use projection to optimize queries by fetching only required fields.

Updated on: 2026-03-15T01:14:33+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements