用于创建数据库和集合的MongoBash脚本
我正在使用vagrant并尝试创建一些bash语句来初始化我的vagrant本地计算机,如服务器配置: 我正在安装Mongo,一切正常,直到我需要创建数据库和一些集合:我想这样做:用于创建数据库和集合的MongoBash脚本,bash,mongodb,shell,ubuntu,vagrant,Bash,Mongodb,Shell,Ubuntu,Vagrant,我正在使用vagrant并尝试创建一些bash语句来初始化我的vagrant本地计算机,如服务器配置: 我正在安装Mongo,一切正常,直到我需要创建数据库和一些集合:我想这样做: mongo use redirect db.createCollection("first") db.createCollection("second") db.createCollection("third") exit 从我的终端和连接到使用ssh的机器都在工作,但我想让这个过程自动化,我已经尝试像上面那样运
mongo
use redirect
db.createCollection("first")
db.createCollection("second")
db.createCollection("third")
exit
从我的终端和连接到使用ssh的机器都在工作,但我想让这个过程自动化,我已经尝试像上面那样运行代码,但没有工作。或者类似于:
mongo --shell use redirect
mongo --shell db.createCollection("first")
如果有人知道怎么做,我会感谢你的帮助
提前感谢。您需要知道,当您开始使用它时,Mongo将创建它,这不是创建集合所必需的。另一方面,如果您想在数据库中创建一些装置,则假定集合已经存在。我认为有两种可能:
--shell
替换为--eval
(请参阅)
可以指定要用作mongo命令参数的数据库。如果它还不存在,它将为您创建。这可能解决了你的问题。请参见手册页中的选项 您还可以使用--eval选项为mongo指定一个要计算的java表达式。因此,以下代码将在bash中执行:
$ mongo redirect --eval 'db.createCollection("first"); db.createCollection("second"); db.createCollection("third")'
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017/redirect
MongoDB server version: 3.4.9
{ "ok" : 1 }
$
你能解释一下备份你的代码吗?
mongo localhost:27017/test myjsfile.js
$ mongo redirect --eval 'db.createCollection("first"); db.createCollection("second"); db.createCollection("third")'
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017/redirect
MongoDB server version: 3.4.9
{ "ok" : 1 }
$
echo 'db.createCollection("first")' | mongo redirect