Mongo 2 天大,我有 SQL 背景,所以请耐心等待。和 mysql 一样,在 MySQL 命令行中,将查询的结果输出到机器上的文件中,非常方便。我试图了解如何在 shell 中对 Mongo 做同样的事情
通过在 shell 之外并执行以下命令,我可以轻松地获得我想要的查询的输出:
mongo localhost:27017/dbname --eval "printjson(db.collectionName.findOne())" > sample.json
上面的方法很好,但是它需要我退出 mongo shell 或者打开一个新的终端选项卡来执行这个命令。如果我可以在 shell 中简单地执行此操作,那将非常方便。
PS:这个问题是我在 SO 上发布的一个问题的一个分支
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" }
我们可以这样做——
mongo db_name --quiet --eval 'DBQuery.shellBatchSize = 2000; db.users.find({}).limit(2000).toArray()' > users.json
shellBatchSize
参数用于确定 mongo 客户端允许打印多少行。它的默认值为 20。
mongo db_name --quiet --eval 'config.set("displayBatchSize", 2000); db.users.find({}).limit(2000).toArray()' > users.json
如果您使用脚本文件、数据库地址和 --quiet 参数调用 shell,您可以将输出(例如使用 print() 生成)重定向到文件:
mongo localhost/mydatabase --quiet myScriptFile.js > output
--quiet
的,谢谢
有一些方法可以做到这一点,而不必退出 CLI 并将 mongo
输出传递到非 tty。
要保存结果为 x
的查询的输出,我们可以执行以下操作将 json 输出直接存储到 /tmp/x.json
:
> EDITOR="cat > /tmp/x.json"
> x = db.MyCollection.find(...).toArray()
> edit x
>
请注意,输出不是严格意义上的 Json,而是 Mongo 使用的方言。
EDITOR="cat > x.json"
cat
替换为 type
。 (writeFile
功能也有效)
edit x
时,它会抱怨 x
之前缺少分号。
let x
,当您使用 edit
命令时,您会得到 SyntaxError: redeclaration of let x
...虽然仍然有效
简单地增加显示的结果数量可能对您有用
在 mongo shell > DBQuery.shellBatchSize = 3000
然后您可以一次性从终端中选择所有结果并粘贴到文本文件中。
这就是我要做的:)
(来自:https://stackoverflow.com/a/3705615/1290746)
结合几个条件:
在 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() );
从终端发送查询
sed
的 -z
键允许将输出视为单个多行字符串
$> mongo localhost --quiet myScriptFile.js | sed -z 's/^.*CUT_TO_HERE\n//' > output.json
在新的 mongodb shell 5.0+ mongosh 中,它集成了 Node.js fs module,因此您可以在新的 mongosh shell 中简单地执行以下操作:
fs.writeFileSync('output.json', JSON.stringify(db.collectionName.findOne()))
这也避免了诸如 ObjectId(...)
包含在 tojson
结果中的问题,它是无效 JSON 字符串。
上面的代码根据文档描述工作:
MongoDB Shell mongosh 是一个功能齐全的 JavaScript 和 Node.js 14.x REPL 环境,用于与 MongoDB 部署进行交互。您可以使用 MongoDB Shell 直接使用您的数据库测试查询和操作。
旧的 mongo
shell已经标记为 Legacy,因此请尽可能使用 mongosh。
.toArray()
转换迭代响应,没有它会出现错误“将循环结构转换为 JSON”
不定期副业成功案例分享