Is there any way to see the MongoDB results in a better format?


Yes, you can use the findOne(). Following is the syntax −

db.yourCollectionName.findOne();

You can use toArray() as well −

db.yourCollectionName.find().toArray();

Let us first create a collection with documents −

> db.betterFormatDemo.insertOne({"StudentName":"Adam Smith","StudentScores":[98,67,89]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7ab826d78f205348bc640")
}
> db.betterFormatDemo.insertOne({"StudentName":"John Doe","StudentScores":[67,89,56]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7ab936d78f205348bc641")
}
> db.betterFormatDemo.insertOne({"StudentName":"Sam Williams","StudentScores":[45,43,33]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7aba76d78f205348bc642")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.betterFormatDemo.find();

This will produce the following output −

{ "_id" : ObjectId("5cd7ab826d78f205348bc640"), "StudentName" : "Adam Smith", "StudentScores" : [ 98, 67, 89 ] }
{ "_id" : ObjectId("5cd7ab936d78f205348bc641"), "StudentName" : "John Doe", "StudentScores" : [ 67, 89, 56 ] }
{ "_id" : ObjectId("5cd7aba76d78f205348bc642"), "StudentName" : "Sam Williams", "StudentScores" : [ 45, 43, 33 ] }

Case 1 − Using findOne().

Following is the query to display the MongoDB results in a better format −

> db.betterFormatDemo.findOne();

This will produce the following output −

{
   "_id" : ObjectId("5cd7ab826d78f205348bc640"),
   "StudentName" : "Adam Smith",
   "StudentScores" : [
      98,
      67,
      89
   ]
}

Case 2 − Using find().toArray().

Following is the query to display the MongoDB results in a better format −

> db.betterFormatDemo.find().toArray();

This will produce the following output −

[
   {
      "_id" : ObjectId("5cd7ab826d78f205348bc640"),
      "StudentName" : "Adam Smith",
      "StudentScores" : [
         98,
         67,
         89
      ]
   },
   {
      "_id" : ObjectId("5cd7ab936d78f205348bc641"),
      "StudentName" : "John Doe",
      "StudentScores" : [
         67,
         89,
         56
      ]
   },
   {
      "_id" : ObjectId("5cd7aba76d78f205348bc642"),
      "StudentName" : "Sam Williams",
      "StudentScores" : [
         45,
         43,
         33
      ]
   }
]

Updated on: 30-Jul-2019

46 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements