mongodb 如何通过shell脚本执行mongo命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4837673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to execute mongo commands through shell scripts?
提问by StackOverFlow
I want to execute mongo
commands in shell script, e.g. in a script test.sh
:
我想mongo
在 shell 脚本中执行命令,例如在脚本中test.sh
:
#!/bin/sh
mongo myDbName
db.mycollection.findOne()
show collections
When I execute this script via ./test.sh
, then the connection to MongoDB is established, but the following commands are not executed.
当我通过 执行此脚本时./test.sh
,会建立与 MongoDB 的连接,但未执行以下命令。
How to execute other commands through shell script test.sh
?
如何通过shell脚本执行其他命令test.sh
?
回答by theTuxRacer
You can also evaluate a command using the --eval
flag, if it is just a single command.
您还可以使用--eval
标志评估命令,如果它只是一个命令。
mongo --eval "printjson(db.serverStatus())"
Please note:if you are using Mongo operators, starting with a $ sign, you'll want to surround the eval argument in single quotes to keep the shell from evaluating the operator as an environment variable:
请注意:如果您使用 Mongo 运算符,以 $ 符号开头,您需要将 eval 参数括在单引号中,以防止 shell 将运算符作为环境变量进行评估:
mongo --eval 'db.mycollection.update({"name":"foo"},{$set:{"this":"that"}});' myDbName
Otherwise you may see something like this:
否则,您可能会看到如下内容:
mongo --eval "db.test.update({\"name\":\"foo\"},{$set:{\"this\":\"that\"}});"
> E QUERY SyntaxError: Unexpected token :
回答by Matt
Put your mongo script into a .js
file.
将您的 mongo 脚本放入一个.js
文件中。
Then execute mongo < yourFile.js
然后执行 mongo < yourFile.js
Ex:
前任:
demo.js //file has your script
demo.js //文件有你的脚本
use sample //db name
show collections
keep this file in "c:\db-scripts"
将此文件保存在“c:\db-scripts”中
Then in cmd prompt go to "c:\db-scripts"
然后在 cmd 提示符下转到“c:\db-scripts”
C:\db-scripts>mongo < demo.js
This will execute the code in mongo and shows the output
这将在 mongo 中执行代码并显示输出
C:\db-scripts>mongo < demo.js
Mongo shell version: 3.0.4
Connecting to: test
switched to db sample
users //collection name
tasks //collection name
bye
C:\db-scripts>
回答by Antonin Brettsnajdr
This works for me under Linux:
这在 Linux 下对我有用:
mongo < script.js
回答by Theo
Put this in a file called test.js
:
把它放在一个名为的文件中test.js
:
db.mycollection.findOne()
db.getCollectionNames().forEach(function(collection) {
print(collection);
});
then run it with mongo myDbName test.js
.
然后用mongo myDbName test.js
.
回答by thaddeusmt
There is an official documentationpage about this as well.
还有一个关于此的官方文档页面。
Examples from that page include:
该页面的示例包括:
mongo server:27017/dbname --quiet my_commands.js
mongo test --eval "printjson(db.getCollectionNames())"
回答by David H. Young
The shell script below also worked nicely for me... definite had to use the redirect that Antonin mentioned at first... that gave me the idea to test the here document.
下面的 shell 脚本对我来说也很好用......肯定必须使用 Antonin 最初提到的重定向......这让我有了测试 here 文档的想法。
function testMongoScript {
mongo <<EOF
use mydb
db.leads.findOne()
db.leads.find().count()
EOF
}
回答by Ed Williams
In my setup I have to use:
在我的设置中,我必须使用:
mongo --host="the.server.ip:port" databaseName theScript.js
回答by John Arrowwood
I use the "heredoc" syntax, which David Young mentions. But there is a catch:
我使用 David Young 提到的“heredoc”语法。但是有一个问题:
#!/usr/bin/sh
mongo <db> <<EOF
db.<collection>.find({
fieldName: { $exists: true }
})
.forEach( printjson );
EOF
The above will NOT work, because the phrase "$exists" will be seen by the shell and substituted with the value of the environment variable named "exists." Which, likely, doesn't exist, so after shell expansion, it becomes:
以上将不起作用,因为短语“$exists”将被shell看到并替换为名为“exists”的环境变量的值。这很可能不存在,所以在 shell 扩展后,它变成:
#!/usr/bin/sh
mongo <db> <<EOF
db.<collection>.find({
fieldName: { : true }
})
.forEach( printjson );
EOF
In order to have it pass through you have two options. One is ugly, one is quite nice. First, the ugly one: escape the $ signs:
为了让它通过,您有两种选择。一个很丑,一个很好看。第一,丑陋的:转义 $ 符号:
#!/usr/bin/sh
mongo <db> <<EOF
db.<collection>.find({
fieldName: { $exists: true }
})
.forEach( printjson );
EOF
I do NOT recommend this, because it is easy to forget to escape.
我不推荐这样做,因为很容易忘记逃跑。
The other option is to escape the EOF, like this:
另一种选择是转义 EOF,如下所示:
#!/usr/bin/sh
mongo <db> <<\EOF
db.<collection>.find({
fieldName: { $exists: true }
})
.forEach( printjson );
EOF
Now, you can put all the dollar signs you want in your heredoc, and the dollar signs are ignored. The down side: That doesn't work if you need to put shell parameters/variables in your mongo script.
现在,您可以在heredoc 中放入所有您想要的美元符号,而美元符号将被忽略。不利的一面:如果您需要将 shell 参数/变量放在 mongo 脚本中,那将不起作用。
Another option you can play with is to mess with your shebang. For example,
你可以玩的另一个选择是弄乱你的shebang。例如,
#!/bin/env mongo
<some mongo stuff>
There are several problems with this solution:
这个解决方案有几个问题:
It only works if you are trying to make a mongo shell script executable from the command line. You can't mix regular shell commands with mongo shell commands. And all you save by doing so is not having to type "mongo" on the command line... (reason enough, of course)
It functions exactly like "mongo <some-js-file>" which means it does not let you use the "use <db>" command.
它仅在您尝试从命令行制作 mongo shell 脚本可执行文件时才有效。您不能将常规 shell 命令与 mongo shell 命令混合使用。这样做所节省的一切就是不必在命令行上输入“mongo”……(当然,理由足够了)
它的功能与“mongo <some-js-file>”完全一样,这意味着它不允许您使用“use <db>”命令。
I have tried adding the database name to the shebang, which you would think would work. Unfortunately, the way the system processes the shebang line, everything after the first space is passed as a single parameter (as if quoted) to the env command, and env fails to find and run it.
我曾尝试将数据库名称添加到您认为可行的 shebang。不幸的是,系统处理 shebang 行的方式,第一个空格之后的所有内容都作为单个参数(好像被引用)传递给 env 命令,并且 env 无法找到并运行它。
Instead, you have to embed the database change within the script itself, like so:
相反,您必须将数据库更改嵌入脚本本身,如下所示:
#!/bin/env mongo
db = db.getSiblingDB('<db>');
<your script>
As with anything in life, "there is more than one way to do it!"
就像生活中的任何事情一样,“有不止一种方法可以做到!”
回答by Moses Xu
In case you have authentication enabled:
如果您启用了身份验证:
mongo -u username -p password --authenticationDatabase auth_db_name < your_script.js
回答by GSK
Create a script file; write commands:
创建脚本文件;写命令:
#!/bin/sh
mongo < file.js
In file.js
write your mongo query:
在file.js
编写您的 mongo 查询时:
db.collection.find({"myValue":null}).count();