和Mongo在一起两天了,我有SQL背景,所以请容忍我.与mysql一样,使用mysql命令行并将查询结果输出到机器上的文件非常方便.我正在努力理解我如何能对while being in the shell岁的Mongo做到这一点

我可以通过在shell之外并执行以下命令,轻松获得所需查询的输出:

mongo localhost:27017/dbname --eval "printjson(db.collectionName.findOne())" > sample.json

上面的方法很好,但它需要我退出mongo shell或打开一个新的terminal选项卡来执行该命令.如果我能在壳里面的时候简单地做这件事,那将是非常方便的.

注:这个问题是我在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" }

Mongodb相关问答推荐

无法从我的NextJS 14应用程序中的Redux工具包2.0中提取数据

最有效的Mongo聚合来展开和过滤:匹配、展开、匹配与投影和过滤

Tableau 与 Mongo DB Atlas by MongoDB 的连接缓存问题

MongoDB - 将数组元素转换为新字段

MongoDB - 将对象转换为数组

将子元素的数组值提取到 mongodb 中的单个数组中?

使用特定关键字和邻近度进行查询和过滤

通过 docker 运行的 MongoDB 服务器无法互相看到(名称解析中的临时故障)

Mongo C#忽略属性

MongoDB:插入重复键更新

根据 Month 删除 mongodb 中的旧记录

MongoDB 的 Java 语法

Node.js 和 Passport 对象没有方法 validPassword

Node.js MongoDB Upsert 更新

Golang + MongoDB 嵌入类型(将一个 struct 嵌入到另一个 struct 中)

NumberLong和简单整数之间的MongoDB区别?

在安装的 MongoDB homebrew 中设置 dbpath (Mac OS)

如何将转储文件夹导入 mongodb 数据库?

如何在mongoDB中检索其值以特定字符结尾的文档

判断字段是否存在于数组的子文档中