我正在使用当前的mongosh工具运行Mongo查询,这些查询可能返回非常大的结果集,这些结果集可能不适合命令提示符的缓冲区(即使这样做了,手工复制这些结果也会耗时且容易出错)。因此,我希望有能力:
mongosh输送到文本文件,以及下面是我目前正在运行的命令(详细信息屏蔽):
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选项。mongosh文件声称该工具处于Beta模式,并支持mongo功能的某些子集。它是否支持传递查询的能力?
发布于 2021-01-20 10:54:38
同时,这也适用于新的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选项。
发布于 2021-01-20 09:28:39
以下是蒙戈的作品(我还没有尝试过蒙戈语)
mongo --eval "db=db.getSiblingDB('DB NAME'); printjson(db.COLLECTION.findOne())" > output.txt --quiet所以你的会变成:
mongo "mongodb://10.20.30.40:26017" --username my_username --password my_password --authenticationDatabase my_database --eval "db=db.getSiblingDB('my_database'); printjson(db.my_collection.count())" > output.txt --quiet发布于 2022-09-14 22:59:44
正如mongoDB文档中提到的,您可以编写js脚本,并在命令行中使用-file选项。
mongosh --norc --quiet --file "test_script.js" > output.txt编写查询的输出,如:db.<collection_name>.findOne();
在jscript中使用以下语法:printjson ( db.<collection_name>.findOne() );
更多细节:https://www.mongodb.com/docs/mongodb-shell/write-scripts/
https://stackoverflow.com/questions/65806112
复制相似问题