How do I get email-id from a MongoDB document and display with print()

To extract email-id values from MongoDB documents and display them using print(), use the forEach() method to iterate through documents and access the email field with dot notation.

Syntax

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

Sample Data

db.demo690.insertMany([
    {"UserName": "John", "UserEmailId": "John@gmail.com"},
    {"UserName": "Bob", "UserEmailId": "Bob@gmail.com"},
    {"UserName": "David", "UserEmailId": "David@gmail.com"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5ea6db31551299a9f98c939c"),
        ObjectId("5ea6db3c551299a9f98c939d"),
        ObjectId("5ea6db47551299a9f98c939e")
    ]
}

Display All Documents

db.demo690.find();
{ "_id" : ObjectId("5ea6db31551299a9f98c939c"), "UserName" : "John", "UserEmailId" : "John@gmail.com" }
{ "_id" : ObjectId("5ea6db3c551299a9f98c939d"), "UserName" : "Bob", "UserEmailId" : "Bob@gmail.com" }
{ "_id" : ObjectId("5ea6db47551299a9f98c939e"), "UserName" : "David", "UserEmailId" : "David@gmail.com" }

Extract Email-IDs Using forEach() and print()

db.demo690.find().forEach(function(document) {
    print(document.UserEmailId);
});
John@gmail.com
Bob@gmail.com
David@gmail.com

Key Points

  • forEach() iterates through each document returned by find()
  • print() outputs the value directly to the MongoDB shell
  • Use dot notation to access specific fields: document.fieldName

Conclusion

Combine find(), forEach(), and print() to extract and display specific field values from MongoDB documents. This approach provides a simple way to output field data directly in the MongoDB shell.

Updated on: 2026-03-15T03:39:17+05:30

513 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements