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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With