8

I'm using vagrant and trying to create some bash sentences to initialize my vagrant local machine like the server configuration:

I'm installing Mongo and everything was ok untill i need to create the database and some collections: I would like to do that:

mongo 
use redirect
db.createCollection("first")
db.createCollection("second")
db.createCollection("third")
exit

From my terminal and conecting to the machine with ssh is working, but i would like to make this process automatic, i have try to run the code exactly like above and is not working. Or something like:

mongo --shell use redirect
mongo --shell db.createCollection("first")

If somebody knows how to do this i will appreciate some help.

Thanks in advance.

4 Answers 4

2

You need to know that is non required to create the collections, when you start to use it Mongo will create it. On the other hand if you want to create some fixtures into the database assume the collection are already there.

Sign up to request clarification or add additional context in comments.

Comments

2

You can specify the database you want to use as an argument to the mongo command. If it does not yet exist, it will be created for you. That probably solves your problem. See the option in the manpage.

You can further specify a java expression for mongo to evaluate, using the --eval option. So the following will execute your code in, for example, 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 }
$

Comments

1

I see 2 possibilities for you to do that :

  1. replace --shell with --eval (see http://docs.mongodb.org/master/tutorial/write-scripts-for-the-mongo-shell/#eval-option)

    mongo --shell db.createCollection("first")
    
  2. put your sequence of step in a js file and run (see http://docs.mongodb.org/master/tutorial/write-scripts-for-the-mongo-shell/#execute-a-javascript-file)

    mongo localhost:27017/test myjsfile.js
    

Comments

0
echo 'db.createCollection("first")' | mongo redirect

1 Comment

can you provide an explanation to backup your code?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.