Specifically, I want to print the results of a mongodb find()
to a file. The JSON object is too large so I'm unable to view the entire object with the shell window size.
-
1Came here through search years later: The mongo shell output is not a valid json but some JavaScript. Look at the output of Object IDs and Dates as a function call to 'ObejctId()` and 'ISODate()'. And there will be "NaN"s, not "null"s. A bit anoying, so some regex is still needed to get a json that can be used with e.g. jq – A. Rabus Sep 16 '21 at 08:55
11 Answers
The shell provides some nice but hidden features because it's an interactive environment.
When you run commands from a javascript file via mongo commands.js you won't get quite identical behavior.
There are two ways around this.
(1) fake out the shell and make it think you are in interactive mode
$ mongo dbname << EOF > output.json
db.collection.find().pretty()
EOF
or
(2) use Javascript to translate the result of a find()
into a printable JSON
mongo dbname command.js > output.json
where command.js contains this (or its equivalent):
printjson( db.collection.find().toArray() )
This will pretty print the array of results, including [ ]
- if you don't want that you can iterate over the array and printjson()
each element.
By the way if you are running just a single Javascript statement you don't have to put it in a file and instead you can use:
$ mongo --quiet dbname --eval 'printjson(db.collection.find().toArray())' > output.json

- 5,087
- 2
- 33
- 32

- 41,784
- 5
- 109
- 133
-
command.js has to be a readable file that exists in your current directory and which has the javascript you want to run. – Asya Kamsky Sep 19 '13 at 19:49
-
How do I do it for a remote mongo db? I tried `mongo blah.mongolab.com:33478/blah -u user -p pass --eval "my query" >> dump.txt` but it gave me `JavaScript execution failed: SyntaxError: Unexpected token ILLEGAL`. – Sheharyar Dec 05 '13 at 06:39
-
that error means what's inside your quotes after --eval is not legal syntax. I recommend using single quotes outside whole expressions and if you have need for quotes inside of it use double quotes for that. – Asya Kamsky Jan 08 '14 at 16:23
-
2Option 2 is really the only option if you have more than a handful of results, since in option 1 it'll just stop at 'Type "it" for more'. – Tomty Jan 08 '15 at 17:40
-
3not really @Tomty - the size of shell batch is controllable with a variable inside the shell. you can put DBQuery.shellBatchSize=10000 into your .mongodbrc.js file and it will "stop" after 10000 results instead of 20. – Asya Kamsky Jan 10 '15 at 15:18
-
Of course you can @AsyaKamsky, but A) That's not mentioned anywhere in the answer. B) That's still limited. C) Why would you? Stuff like that happens because the shell is meant to be interactive, and "faking it out" seems unnecessary. – Tomty Jan 15 '15 at 18:49
-
I agree that faking it out is "wrong" but it is possible. but that's why I gave the "real" answer that doesn't require faking. – Asya Kamsky Jan 16 '15 at 00:19
-
-
is there anyway to access these features when running mogosh wthin compasss? – boardtc Nov 16 '22 at 22:24
Since you are doing this on a terminal and just want to inspect a record in a sane way, you can use a trick like this:
mongo | tee somefile
Use the session as normal - db.collection.find().pretty()
or whatever you need to do, ignore the long output, and exit. A transcript of your session will be in the file tee
wrote to.
Be mindful that the output might contain escape sequences and other garbage due to the mongo shell expecting an interactive session. less
handles these gracefully.

- 1,065
- 8
- 20
Just put the commands you want to run into a file, then pass it to the shell along with the database name and redirect the output to a file. So, if your find command is in find.js
and your database is foo
, it would look like this:
./mongo foo find.js >> out.json

- 21,336
- 4
- 65
- 85
-
This did not work for me, only printed out shell version and db name to `out.json`. `mongo foo < find.js > out.json` did work. – James Brown Feb 11 '18 at 10:15
-
2this answer was written before the tools were rewritten in Go and many versions ago, unless you are using something very old, then that's probably why it's not working for you – Adam Comerford Feb 11 '18 at 20:56
Put your query (e.g. db.someCollection.find().pretty()
) to a javascript file, let's say query.js
. Then run it in your operating system's shell using command:
mongo yourDb < query.js > outputFile
Query result will be in the file named 'outputFile'.
By default Mongo prints out first 20 documents IIRC. If you want more you can define new value to batch size in Mongo shell, e.g.
DBQuery.shellBatchSize = 100
.

- 1,046
- 2
- 16
- 29
-
This. Don't be misdirected by `.js` extension. You can write all those nice mongo shell queries without changing them at all. – A.D. Oct 09 '17 at 14:07
Using print
and JSON.stringify
you can simply produce a valid JSON
result.
Use --quiet
flag to filter shell noise from the output.
Use --norc
flag to avoid .mongorc.js
evaluation. (I had to do it because of a pretty-formatter that I use, which produces invalid JSON output)
Use DBQuery.shellBatchSize = ?
replacing ?
with the limit of the actual result to avoid paging.
And finally, use tee
to pipe the terminal output to a file:
// Shell:
mongo --quiet --norc ./query.js | tee ~/my_output.json
// query.js:
DBQuery.shellBatchSize = 2000;
function toPrint(data) {
print(JSON.stringify(data, null, 2));
}
toPrint(
db.getCollection('myCollection').find().toArray()
);
Hope this helps!

- 778
- 8
- 10
I managed to save result with writeFile() function.
> writeFile("/home/pahan/output.txt", tojson(db.myCollection.find().toArray()))
Mongo shell version was 4.0.9

- 358
- 4
- 9
In the new mongodb shell 5.0+ mongosh, it integrate the Node.js fs module, so you can simply do below in the new mongosh shell for pretty print the output:
fs.writeFileSync('output.json', JSON.stringify(db.test.find().toArray(), null, 2))
Without any problems such as the ObjectId
has been stripped, etc., which is better than the printjson
or .pretty()
.
The above code can work as the description denotes:
The MongoDB Shell, mongosh, is a fully functional JavaScript and Node.js 14.x REPL environment for interacting with MongoDB deployments. You can use the MongoDB Shell to test queries and operations directly with your database.
The old mongo
shell also marked as Legacy, so you should move to this new way.

- 476
- 5
- 6
Using this answer from Asya Kamsky, I wrote a one-line bat script for Windows. The line looks like this:
mongo --quiet %1 --eval "printjson(db.%2.find().toArray())" > output.json
Then one can run it:
exportToJson.bat DbName CollectionName

- 1
- 1

- 2,751
- 18
- 20
Also there is mongoexport for that, but I'm not sure since which version it is available.
Example:
mongoexport -d dbname -c collection --jsonArray --pretty --quiet --out output.json

- 5,154
- 2
- 27
- 38
you can use this command to acheive it:
mongo admin -u <userName> -p <password> --quiet --eval "cursor = rs.status(); printjson(cursor)" > output.json

- 2,385
- 18
- 35
- 46

- 11
- 3