Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongo shell script won't let me include "use <database>"

32-bit mongo 2.0.1 on a windows XP machine

//script filename: test.js  (one line shell script file to store a person) db.cTest.save({Name: "Fred", Age:21}); 

run against database dbTest by entering the following 2 shell commands:

    > use dbTest     switched to dbTest     > load("test.js") 

So far, so good.

But if I try and include the "use" statement in the script it fails:

//script filename: test.js  (including "use" statement) use dbTest; db.cTest.save({Name: "Fred", Age:21}); 

fails with error msg as follows:

    > load("test.js")     SyntaxError: missing ; before statement     Mon Dec 19 11:56:31: Error: error loading js file temp.js (shell):1 

Adding or removing semicolons to test.js doesn't seem to matter.

So how do you put a "use" directive into a mongo shell script?

like image 493
tpascale Avatar asked Dec 19 '11 17:12

tpascale


1 Answers

In a mongo script you can use the db.getSiblingDB('new_db_name') to get a reference of a new database. So, it it not mandatory to give the database name in the command line. You can use the script.js:

db = db.getSiblingDB('new_db_name'); print(db);  // the rest of your code for database "new_db_name" 

and the output of this script is (invoked with mongo script.js):

MongoDB shell version: 2.2.2 connecting to: test sag 
like image 117
4 revs, 2 users 76% Avatar answered Sep 20 '22 18:09

4 revs, 2 users 76%