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



For this, use forEach() along with print() to display the email-id values. Let us create a collection with documents −

> db.demo690.insertOne({"UserName":"John","UserEmailId":"John@gmail.com"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ea6db31551299a9f98c939c") } > db.demo690.insertOne({"UserName":"Bob","UserEmailId":"Bob@gmail.com"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ea6db3c551299a9f98c939d") } > db.demo690.insertOne({"UserName":"David","UserEmailId":"David@gmail.com"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ea6db47551299a9f98c939e") }

Display all documents from a collection with the help of find() method −

> db.demo690.find();

This will produce the following output −

{ "_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" }

Following is the query to get email-id from a MongoDB document and print using print() −

> db.demo690.find().forEach(function(document) { ...    print(document.UserEmailId); ... });

This will produce the following output −

John@gmail.com Bob@gmail.com David@gmail.com
Updated on: 2020-05-14T09:29:48+05:30

468 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements