mongo shell script won't let me include “use

前端 未结 3 1509
失恋的感觉
失恋的感觉 2020-12-25 12:26

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})         


        
相关标签:
3条回答
  • 2020-12-25 12:43

    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")

    0 讨论(0)
  • 2020-12-25 12:57

    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
    
    0 讨论(0)
  • 2020-12-25 12:58

    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
    
    0 讨论(0)
提交回复
热议问题