简体   繁体   English

如何处理 mongo 脚本中的命令行参数?

[英]How do I handle command-line arguments in a mongo script?

I've been working on some simple scripts to run on mongo from the bash command-line.我一直在编写一些简单的脚本,以便从 bash 命令行在 mongo 上运行。 Originally, I ran them as follows:最初,我按如下方式运行它们:

$ mongo dbname script.js

but I recently came across mikemaccana's answer, https://stackoverflow.com/a/23909051/2846766 , indicating the use of mongo as an interpreter so I can just execute script.js (or any name I choose, with or without the .js) from the command line.但我最近遇到了 mikemaccana 的答案https://stackoverflow.com/a/23909051/2846766 ,表明使用 mongo 作为解释器,所以我可以只执行 script.js(或我选择的任何名称,带或不带 . js) 从命令行。

$ script.js

I think it's brilliant and clean, but now I'd like to pass in a database name as a command line argument.我认为它很棒而且很干净,但现在我想传入一个数据库名称作为命令行参数。

$ script.js dbname

Here I use the bash-style "$1" to demonstrate what I'm doing in script.js.在这里,我使用 bash 样式的“$1”来演示我在 script.js 中所做的事情。

#!/usr/bin/env mongo
var db = new Mongo().getDB($1);
// Do other things with db, once I resolve the name from the command line.

This results in a "ReferenceError: $1 is not defined ...", which is not surprising.这会导致“ReferenceError: $1 is not defined ...”,这并不奇怪。 But how would I reference command line arguments?但是我将如何引用命令行参数? Is this going to be a mongo convention?这将是一个 mongo 大会吗? a javascript convention?一个javascript约定? Is it possible?是否可以? It would make my command-line experience with mongo much better aesthetically.这将使我在 mongo 的命令行体验在美学上更好。

Currently there is no way to do this using the mongo shell... 当前无法使用mongo shell来执行此操作...

https://groups.google.com/forum/#!topic/mongodb-user/-pO7Cec6Sjc https://groups.google.com/forum/#!topic/mongodb-user/-pO7Cec6Sjc

... try using a bash script (or other scripting language you are comfortable with) if you want to get a similar command line experience. ...如果您想获得类似的命令行体验,请尝试使用bash脚本(或其他您喜欢的脚本语言)。

简而言之, 如何将参数传递给Mongo脚本是不可能的,但是答案中给出了几种解决方法(此处不再赘述)。

You can pass args to your script through您可以通过 args 传递给您的脚本

mongo --eval 'var databasePassword="password"' script.js

and you can access databasePassword value inside script.js你可以在script.js访问 databasePassword 值

db.auth({ user: 'testUser, pwd: databasePassword });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM