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

标签 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 上发布的一个问题的一个分支。

最佳答案

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/

相关文章:

mongodb - mongoose $elemMatch 返回所有结果,而不是仅第一个

python - 退格键似乎在 python 中不起作用

java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?

python - 在 MongoDB 中重用 Cursor 对象

mongodb - 更新/删除 MongoDB 集合中的子文档

node.js - 使用 Nodejs 连接 MongoDB 时出现 ReplicaSetNoPrimary 和 MongoServerSelectionError 错误

javascript - Chrome 上出现错误 "Provisional headers are shown"

ruby-on-rails - 使用 Mongo 运行 'bootstrap:themed' 时出现 Twitter Bootstrap 错误

mongodb - 如何在 Rails 控制台中查询特定的 MongoDB 集合字段?

cocoa - 所有 Cocoa key 代码在哪里?