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 wi
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.
you can use this command to acheive it:
mongo admin -u <userName> -p <password> --quiet --eval "cursor = rs.status(); printjson(cursor)" > output.json
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
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
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
As answer by Neodan mongoexport is quite useful with -q
option for query. It also convert ObjectId
to standard format of JSON "$oid"
. E.g:
mongoexport -d yourdb -c yourcol --jsonArray --pretty -q '{"field": "filter value"}' -o output.json