MongoDB

MongoDB Shell Pretty Print

The MongoDB Shell is an incredibly powerful utility that every MongoDB developer should use. However, although it can provide convenience in a minimal and terminal based environment, it does not provide comprehensible and easy to read output.

In this article, we will show you a Mongo Shell function that is easy to use but allows you to get organized and get a human-readable output from MongoDB queries. Having a readable output can make a huge difference instead of diving into the external tools such as grep and jq.

Let’s dive in.

MongoDB Pretty Print Method Syntax

The method syntax is shown in the following:

db.collection.find(<query>).pretty()

The method configures the MongoDB cursor to show the output in a well-formatted and easy to read format.

Examples:

Consider the examples shown in the following:

Suppose we make a cursor as shown in the following query:

db.film.find({"_id": 20})

The given query returns the document with the specified ID as shown in the following output:

{ _id: 20,
  Actors:
   [ { 'First name': 'CARMEN', 'Last name': 'HUNT', actorId: 52 },
     { 'First name': 'WALTER', 'Last name': 'TORN', actorId: 102 },
     { 'First name': 'ED', 'Last name': 'MANSFIELD', actorId: 136 },
     { 'First name': 'EWAN', 'Last name': 'GOODING', actorId: 139 },
     { 'First name': 'IAN', 'Last name': 'TANDY', actorId: 155 },
     { 'First name': 'LAURA', 'Last name': 'BRODY', actorId: 159 } ],
  Category: 'Music',
  Description: 'A Boring Drama of a Woman And a Squirrel who must Conquer a Student in A Baloon',
  Length: '79',
  Rating: 'R',
  'Rental Duration': '4',
  'Replacement Cost': '23.99',
  'Special Features': 'Commentaries,Deleted Scenes,Behind the Scenes',
  Title: 'AMELIE HELLFIGHTERS' }

We can use the cursor.pretty() method which allows the cursor to return the document in a pretty and easier to read format.

An example is as shown in the following:

db.film.find({"_id": 20}).pretty()

Resulting output:

MongoDB Set Pretty Print as Default

Instead of calling the pretty() method every time, we can tell the MongoDB to use the Pretty Print as default cursor output with the following command:

echo DBQuery.prototype._prettyShell = true >>  ~/.mongorc.js

Replace the given command with the path to your “.mongorc.js” file.

Conclusion

In this post, you learned how to use the Mongo Shell Pretty print feature which allows you to view the results of a given query in an easy-to-read format.

Happy coding!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list