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

在 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" }

https://stackoverflow.com/questions/22565231/

相关文章:

javascript - Mongoose 中的id和_id有什么区别?

node.js - MongoDB + nodejs : how to query ISODate

node.js - 如何在同一个语句中使用填充和聚合?

mongodb - 查询 MongoDB 中的数组数组

c# - 如何使用官方 c# 驱动程序在 MongoDB 中使用 Update.Set 更新多个字段

node.js - 从 node.js 连接到 mongodb 时出现 ECONNREFUSED 错

mongodb - mongorestore 失败 : no reachable servers

python - 如何关闭 mongodb python 连接?

node.js - Mongoose 模式创建

mongodb - 如何解决错误 :dbpath (/data/db/) does not exis