在mongo shell中将Mongo查询输出打印到文件 [英] Printing Mongo query output to a file while in the mongo shell
问题描述
2天与Mongo我有一个SQL背景所以请耐心等待。与mysql一样,在MySQL命令行中将查询结果输出到计算机上的文件非常方便。我试图理解我如何对Mongo做同样的事情,同时在shell中
2 days old with Mongo and I have a SQL background so bear with me. As with mysql, it is very convenient to be in the MySQL command line and output the results of a query to a file on the machine. I am trying to understand how I can do the same with Mongo, while being in the shell
我可以轻松获得查询的输出我想通过在shell之外并执行以下命令:
I can easily get the output of a query I want by being outside of the shell and executing the following command:
mongo localhost:27017/dbname --eval "printjson(db.collectionName.findOne())" >> sample.json
上面的方法很好,但它要求我退出mongo shell或打开一个新的终端选项卡执行此命令。如果我仍然可以在shell内部执行此操作,那将非常方便。
The above way is fine, but it requires me to exit the mongo shell or open a new terminal tab to execute this command. It would be very convenient if I could simply do this while still being inside the shell.
PS:问题是我在 SO
推荐答案
AFAIK,没有输出到文件的交互选项,之前有一个与之相关的问题:将mongodb shell输出打印到文件
AFAIK, there is no a interactive option for output to file, there is a previous SO question related with this: Printing mongodb shell output to File
但是,如果使用tee命令调用shell,则可以记录所有shell会话:
However, you can log all the shell session if you invoked the shell with tee command:
$ 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
然后你会得到一个包含这个内容的文件:
Then you'll get a file with this content:
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输出,可以使用命令类似于:
To remove all the commands and keep only the json output, you can use a command similar to:
tail -n +3 file.txt | egrep -v "^>|^bye" > output.json
然后你会得到:
{ "this" : "is a test" }
{ "this" : "is another test" }
这篇关于在mongo shell中将Mongo查询输出打印到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!