我正在使用当前的 mongosh
工具来运行 Mongo 查询,它可能会返回非常大的结果集,这些结果集可能不适合命令提示符的缓冲区(即使可以,也复制此类结果手工操作既费时又容易出错)。因此,我希望能够:
- 将
mongosh
的输出通过管道传输到文本文件,并且 - 还传入 Mongo 脚本或查询以从命令行运行
这是我当前正在运行的命令(隐藏了详细信息):
mongosh "mongodb://10.20.30.40:26017" --username my_username --password my_password
--authenticationDatabase my_database > output.txt
这是我在 output.txt
中看到的当前输出:
Current sessionID: 1ee96e0f6025ec328ea25ccc
Connecting to: mongodb://10.20.30.40:26017
Using MongoDB: 3.4.13
Using Mongosh Beta: 0.0.6
For more information about mongosh, please see our docs: https://docs.mongodb.com/mongodb-shell/
[1G[0J> [3G
所以看起来重定向到输出文件是有效的。但是,我似乎无法弄清楚如何使用对命令行工具的实际查询来指定 Mongo 脚本。例如,如果我想指定以下简单的计数查询,我该怎么做?
db.getCollection('my_collection').count();
理想情况下,我希望 output.txt
只有一行包含此集合的计数。
早期的 mongo
命令行工具似乎有多种管道查询方式,例如通过指定脚本或使用 --eval
选项。 documentation for mongosh声称此工具处于 Beta 模式并支持 mongo
功能的某些子集。它是否支持传递查询的能力?
最佳答案
同时这也适用于新的 mongosh
,确保您下载了最新版本(1.1.9 或更新版本)
echo "db.getCollection('my_collection').countDocuments({});" | mongosh --norc --quiet > output.txt
mongosh --norc --quiet > output.txt <<EOF
db.getCollection('my_collection').countDocuments({});
EOF
mongosh --norc --quiet --eval "db.getCollection('my_collection').countDocuments({})" > output.txt
请注意,使用经典的 mongo
shell,您会收到此警告:
================
Warning: the "mongo" shell has been superseded by "mongosh",
which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
We recommend you begin using "mongosh".
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
我认为这不是真的,我还没有看到新的 mongosh
作为 mongosh
的继任者。但我不得不承认,它正在变得越来越好。
消除此警告的唯一方法是 --eval
选项。
关于mongodb - 将 mongosh MongoDB Shell 的输出通过管道传输到输出文件 (Windows),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65806112/