在mongo shell中将Mongo查询输出打印到文件

时间:2014-03-21 17:12:50

标签: mongodb io mongodb-query mongo-shell

与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

上发布的问题的分支

6 个答案:

答案 0 :(得分:48)

AFAIK,没有输出到文件的交互式选项,之前有一个与此相关的SO问题:Printing mongodb shell output to File

但是,如果使用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" }

答案 1 :(得分:15)

如果使用script-file,db address和--quiet参数调用shell,则可以将输出(例如print())重定向到文件:

mongo localhost/mydatabase --quiet myScriptFile.js > output 

答案 2 :(得分:10)

我们可以这样做 -

mongo db_name --quiet --eval 'DBQuery.shellBatchSize = 2000; db.users.find({}).limit(2000)' > users.json

shellBatchSize参数用于确定允许打印的mongo客户端的行数。它的默认值是20。

答案 3 :(得分:3)

简单地增加显示的结果数量可能对您有用

  

在mongo shell中> DBQuery.shellBatchSize = 3000

然后您可以一次性从终端中选择所有结果并粘贴到文本文件中。

这就是我要做的事情:)

(来自:https://stackoverflow.com/a/3705615/1290746

答案 4 :(得分:3)

结合几个条件:

  • 在JS文件中编写mongo查询并从终端发送
  • 以编程方式切换/定义数据库
  • 输出所有找到的记录
  • 切割初始输出线
  • 将输出保存到JSON文件

<强> myScriptFile.js

// Switch current database to "mydatabase"
db = db.getSiblingDB('mydatabase');

// The mark for cutting initial output off
print("CUT_TO_HERE");

// Main output
// "toArray()" method allows to get all records
printjson( db.getCollection('jobs').find().toArray() );

从终端发送查询

-z

sed键允许将输出视为单个多行字符串

$&GT; mongo localhost --quiet myScriptFile.js | sed -z 's/^.*CUT_TO_HERE\n//' > output.json

答案 5 :(得分:3)

有许多方法可以不必退出CLI并将mongo输出到非tty管道。

要保存结果为x的查询的输出,我们可以执行以下操作将json输出直接存储到/tmp/x.json

> EDITOR="cat > /tmp/x.json"
> x = db.MyCollection.find(...).toArray()
> edit x
>

请注意,输出严格来说不是Json,而是Mongo使用的方言。

相关问题