How to Prettify Exported MongoDB Documents in mongoexport

When you use mongoexport to export documents in MongoDB, you have the option of “prettifying” them.

By this I mean, instead of the document being presented on one long line, it instead includes line breaks, indents, etc to make it easier to read.

To do this in mongoexport, use the --pretty parameter.

Example

Suppose we have a collection called posts with the following documents:

{ "_id" : 1, "title" : "Web", "body" : "blah 1", "tags" : [ "html", "css", "sql", "xml" ] }
{ "_id" : 2, "title" : "Animals", "body" : "blah blah 2", "tags" : [ "cats", "dogs" ] }
{ "_id" : 3, "title" : "Oceans", "body" : "blah blah blah 3", "author" : { "name" : "Bart Pitt", "Email" : "[email protected]" } }

We can use the mongoexport utility to export that collection to a JSON file.

Without Prettify

First, here’s an example that does not use the --pretty parameter:

mongoexport --db=krankykranes --collection=posts --out=posts.json

That code does not use the --pretty parameter, and therefore the resulting JSON file looks like this:

{"_id":1.0,"title":"Web","body":"blah 1","tags":["html","css","sql","xml"]}
{"_id":2.0,"title":"Animals","body":"blah blah 2","tags":["cats","dogs"]}
{"_id":3.0,"title":"Oceans","body":"blah blah blah 3","author":{"name":"Bart Pitt","Email":"[email protected]"}}

With Prettify

First, here’s an example that does use the --pretty parameter:

mongoexport --db=krankykranes --collection=posts --pretty --out=posts.json

That code uses the --pretty parameter, and therefore the resulting JSON file looks like this:

{
	"_id": 1.0,
	"title": "Web",
	"body": "blah 1",
	"tags": [
		"html",
		"css",
		"sql",
		"xml"
	]
}
{
	"_id": 2.0,
	"title": "Animals",
	"body": "blah blah 2",
	"tags": [
		"cats",
		"dogs"
	]
}
{
	"_id": 3.0,
	"title": "Oceans",
	"body": "blah blah blah 3",
	"author": {
		"name": "Bart Pitt",
		"Email": "[email protected]"
	}
}

Now it’s much easier to make out each field/value pair, especially the arrays and embedded documents.