Is there a way to 'pretty' print MongoDB shell output to a file?

前端 未结 10 1832
余生分开走
余生分开走 2020-11-27 09:38

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

相关标签:
10条回答
  • 2020-11-27 10:16

    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.

    0 讨论(0)
  • 2020-11-27 10:16

    you can use this command to acheive it:

    mongo admin -u <userName> -p <password> --quiet --eval "cursor = rs.status(); printjson(cursor)" > output.json

    0 讨论(0)
  • 2020-11-27 10:21

    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
    
    0 讨论(0)
  • 2020-11-27 10:21

    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
    
    0 讨论(0)
  • 2020-11-27 10:21

    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

    0 讨论(0)
  • 2020-11-27 10:22

    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
    
    0 讨论(0)
提交回复
热议问题