在 Mongo 工作 2 天,我有 SQL 背景,所以请耐心等待。和 mysql 一样,在 MySQL 命令行中,将查询的结果输出到机器上的文件中,非常方便。我试图了解如何在 Mongo 中做同样的事情,在 shell 中
我可以通过在 shell 之外并执行以下命令轻松获得我想要的查询的输出:
mongo localhost:27017/dbname --eval "printjson(db.collectionName.findOne())" > sample.json
上面的方法很好,但是需要我退出 mongo shell 或者打开一个新的终端选项卡来执行这个命令。如果我可以在 shell 中简单地执行此操作,那将非常方便。
P.S:这个问题是我在 SO 上发布的一个问题的一个分支。
最佳答案
AFAIK,没有用于输出到文件的交互式选项,之前有一个与此相关的 SO 问题:Printing mongodb shell output to File
但是,如果您使用 tee 命令调用 shell,则可以记录所有 shell session :
$ 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" }
关于mongodb - 在 mongo shell 中将 Mongo 查询输出打印到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22565231/