两天大的蒙戈,我有一个SQL背景,所以请原谅我。与mysql一样,在MySQL命令行中并将查询结果输出到机器上的文件非常方便。我正在努力理解如何在进入shell时对mongo.mengo做同样的事情。
通过在shell之外执行以下命令,我可以轻松地获得我想要的查询的输出:
mongo localhost:27017/dbname --eval "printjson(db.collectionName.findOne())" > sample.json上面的方法很好,但是它要求我退出mongo,或者打开一个新的终端选项卡来执行这个命令。如果我能简单地做到这一点,同时仍然在shell中,这将是非常方便的。
P.S:这个问题是我在所以上发布的一个问题的一个分支
发布于 2014-03-21 17:28:30
AFAIK,文件输出没有交互式选项,前面有一个与此相关的问题:将mongodb输出打印到文件
但是,如果使用tee命令调用shell,则可以记录所有shell会话:
$ mongo | tee file.txt
MongoDB shell version: 2.4.2
connecting to: test
> printjson({this: 'is a test'})
{ "this" : "is a test" }
> printjson({this: 'is another test'})
{ "this" : "is another test" }
> exit
bye然后,您将得到一个包含以下内容的文件:
MongoDB shell version: 2.4.2
connecting to: test
> printjson({this: 'is a test'})
{ "this" : "is a test" }
> printjson({this: 'is another test'})
{ "this" : "is another test" }
> exit
bye要删除所有命令并只保留json输出,可以使用类似于以下命令的命令:
tail -n +3 file.txt | egrep -v "^>|^bye" > output.json然后你会得到:
{ "this" : "is a test" }
{ "this" : "is another test" }发布于 2018-04-04 14:55:56
我们可以这样做-
mongo db_name --quiet --eval 'DBQuery.shellBatchSize = 2000; db.users.find({}).limit(2000).toArray()' > users.jsonshellBatchSize参数用于确定允许mongo客户端打印多少行。它的默认值是20。
发布于 2014-12-23 02:04:09
如果使用脚本文件、db地址和--静默参数调用shell,则可以将输出(例如,print() )重定向到文件:
mongo localhost/mydatabase --quiet myScriptFile.js > output https://stackoverflow.com/questions/22565231
复制相似问题