Enable Pretty Print by Default in MongoDB Shell
How to enable Pretty Print by default in MongoDB Shell?
In MongoDB, using "pretty print" in the shell helps display query results in a more readable format, making JSON documents easier to read and debug. By default, MongoDB outputs query results in a single line. However, you can use the .pretty() method to format the output with indentation and line breaks. To make pretty printing the default in the MongoDB shell, you can set an alias or configure your shell to apply .pretty() automatically.
Description :
Pretty printing in MongoDB helps format query results for better readability by indenting JSON documents and breaking them into lines. By default, MongoDB does not pretty print, so you must add .pretty() to each query to format it. To streamline this, you can configure MongoDB to always output results in a pretty format, making it easier to read documents without needing to apply .pretty() manually each time.
Syntax:
The syntax to pretty print a MongoDB query result is:
db.<collection>.find(<query>).pretty()
Explanation:
- <collection>: The collection you're querying.
- <query>: The query you’re running (can be empty for all documents).
- .pretty(): Formats the result with indentation and line breaks.
To automatically pretty print every query in the MongoDB shell, you can use the following workaround.
Example Code:
Here's how you can pretty print and make it the default in the MongoDB shell.
Using .pretty() for a Single Query
Code:
// Query the 'users' collection and pretty print the output
db.users.find().pretty()
Setting Pretty Print as Default in MongoDB Shell
You can add an alias in your MongoDB shell startup file to make pretty printing automatic.
// Place this function in your MongoDB shell startup script
DBQuery.prototype._prettyShell = true;
Explanation:
- db.users.find().pretty()
This command queries the users collection and applies .pretty() to format the results, making them easier to read. - DBQuery.prototype._prettyShell = true;
Adding this line to your MongoDB shell configuration (e.g., in .mongorc.js or a startup script) enables pretty printing for all queries by default. With this setting, any query executed in the MongoDB shell will automatically use the .pretty() format. - .mongorc.js is a startup file that MongoDB loads whenever the shell starts. Placing the DBQuery.prototype._prettyShell = true; line here ensures pretty printing for all sessions.
This approach allows you to avoid typing .pretty() for every query, as MongoDB will automatically apply pretty formatting to all results by default.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/mongodb/snippets/how-to-enable-pretty-print-by-default-in-mongodb-shell.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics