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})
http://www.mongodb.org/display/DOCS/Scripting+the+shell
use dbname
This command does not work in scripted mode. Instead you will need to explicitly define the database in the connection (/dbname in the example above).Alternately, you can also create a connection within the script:
db2 = connect("server:27017/otherdbname")
Well, it still is unfortunate that "load('file.js')" and "mongo file.js" don't actually use the same script interpreter as the interactive mongo shell. Opening the connection explicitly in the script is potentially a violation of the DRY principle because mongo already knows that information. What does work, though, is piping the file into mongo rather than passing its name on the command line:
mongo <file.js
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