Fetching all documents from MongoDB Collection in a beautified form


To fetch documents, use find() in MongoDB. With that, to format the resultant documents, use pretty().

Let us create a collection with documents −

> db.demo306.insertOne({"Name":"Robert","Age":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4ea7c6f8647eb59e562038")
}
> db.demo306.insertOne({"Name":"David","Age":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4ea7cdf8647eb59e562039")
}
> db.demo306.insertOne({"Name":"Mike","Age":25});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4ea7d4f8647eb59e56203a")
}
> db.demo306.insertOne({"Name":"Carol","Age":26});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4ea7dcf8647eb59e56203b")
}

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

> db.demo306.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e4ea7c6f8647eb59e562038"),
   "Name" : "Robert",
   "Age" : 21
}
{
   "_id" : ObjectId("5e4ea7cdf8647eb59e562039"),
   "Name" : "David",
   "Age" : 23
}
{
   "_id" : ObjectId("5e4ea7d4f8647eb59e56203a"),
   "Name" : "Mike",
   "Age" : 25
}
{
   "_id" : ObjectId("5e4ea7dcf8647eb59e56203b"),
   "Name" : "Carol",
   "Age" : 26
}

Updated on: 01-Apr-2020

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements