如何处理 mongo 脚本中的命令行参数?
Posted
技术标签:
【中文标题】如何处理 mongo 脚本中的命令行参数?【英文标题】:How do I handle command-line arguments in a mongo script? 【发布时间】:2014-08-12 16:28:18 【问题描述】:我一直在编写一些简单的脚本,以便从 bash 命令行在 mongo 上运行。最初,我按如下方式运行它们:
$ mongo dbname script.js
但我最近遇到了 mikemaccana 的回答 https://***.com/a/23909051/2846766,表明使用 mongo 作为解释器,因此我可以从命令行执行 script.js(或我选择的任何名称,带或不带 .js)。
$ script.js
我认为它很棒而且很干净,但现在我想传入一个数据库名称作为命令行参数。
$ script.js dbname
这里我使用 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.
这会导致“ReferenceError: $1 is not defined ...”,这并不奇怪。但是我将如何引用命令行参数?这将是一个 mongo 大会吗?一个javascript约定?可能吗?这将使我在 mongo 上的命令行体验在美学上更好。
【问题讨论】:
【参考方案1】:您可以通过 args 将 args 传递给您的脚本
mongo --eval 'var databasePassword="password"' script.js
你可以访问script.js
里面的databasePassword值
db.auth( user: 'testUser, pwd: databasePassword );
【讨论】:
【参考方案2】:How to pass argument to Mongo Script 的副本 简而言之,这是不可能的,但答案中给出了几种解决方法(此处不再重复)。
【讨论】:
【参考方案3】:目前没有办法使用 mongo shell 来做到这一点...
https://groups.google.com/forum/#!topic/mongodb-user/-pO7Cec6Sjc
...如果您想获得类似的命令行体验,请尝试使用 bash 脚本(或您熟悉的其他脚本语言)。
【讨论】:
以上是关于如何处理 mongo 脚本中的命令行参数?的主要内容,如果未能解决你的问题,请参考以下文章
[100 Tips About Shell] Shell中是如何处理换行符的