有没有办法'漂亮'将MongoDB shell输出打印到文件? [英] Is there a way to 'pretty' print MongoDB shell output to a file?

查看:2003
本文介绍了有没有办法'漂亮'将MongoDB shell输出打印到文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具体来说,我想将mongodb find()的结果打印到文件中。 JSON对象太大,所以我无法用shell窗口大小查看整个对象。

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.

有两种解决方法。

(1)伪造外壳并让它认为你是互动的模式

(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆