有没有办法“漂亮"地将 MongoDB shell 输出打印到文件中? [英] Is there a way to 'pretty' print MongoDB shell output to a file?
问题描述
具体来说,我想将 mongodb find()
的结果打印到文件中.JSON 对象太大,因此我无法使用外壳窗口大小查看整个对象.
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.
推荐答案
shell 提供了一些不错但隐藏的功能,因为它是一个交互式环境.
The shell provides some nice but hidden features because it's an interactive environment.
当您通过 mongo commands.js 从 javascript 文件运行命令时,您不会得到完全相同的行为.
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) 伪造 shell 并让它认为您处于交互模式
(1) fake out the shell and make it think you are in interactive mode
$ mongo dbname << EOF > output.json
db.collection.find().pretty()
EOF
或
(2) 使用 Javascript 将 find()
的结果转换为可打印的 JSON
or
(2) use Javascript to translate the result of a find()
into a printable JSON
mongo dbname command.js > output.json
其中 command.js 包含此(或其等效项):
where command.js contains this (or its equivalent):
printjson( db.collection.find().toArray() )
这将漂亮地打印结果数组,包括 [ ]
- 如果您不希望可以迭代数组和 printjson()
每个元素.
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.
顺便说一句,如果您只运行一个 Javascript 语句,则不必将其放入文件中,而是可以使用:
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
这篇关于有没有办法“漂亮"地将 MongoDB shell 输出打印到文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!