Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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 byfind() -
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.
Advertisements
