Home > database >  mongo shell command not accept use db command
mongo shell command not accept use db command

Time:04-12

i am trying to pull records form mongo data base with json format to do that i am running below js :

conatin of get_DRMPhysicalresources_Data.js
    cursor = db.physicalresources.find().limit(10)
    while ( cursor.hasNext() ){
       print( JSON.stringify(cursor.next()) );
    }

the command i run to get the records : 
    mongo host_name:port/data_base_name -u user -p 'password' --eval "load(\"get_DRMPhysicalresources_Data.js\")" > DRMPhysicalresources.json

and i am able to get the result as josn formate inside DRMPhysicalresources.json , now i want to switch to other data base using use command i try add use db as below :

 conatin of get_DRMPhysicalresources_Data.js
    use db2_test
    cursor = db.physicalresources.find().limit(10)
    while ( cursor.hasNext() ){
       print( JSON.stringify(cursor.next()) );
    }
    the command i run to get the records : 
    mongo host_name:port/data_base_name -u user -p 'password' --eval "load(\"get_DRMPhysicalresources_Data.js\")" > DRMPhysicalresources.json

but i am getting below errors :

MongoDB shell version v4.2.3
connecting to: "some data base info"
Implicit session: session { "id" : UUID("8c85c6af-ebed-416d-9ab8-d6739a4230cb") }
MongoDB server version: 4.4.11
WARNING: shell and server versions do not match
2022-04-11T13:39:30.121 0300 E  QUERY    [js] uncaught exception: SyntaxError: unexpected token: identifier :
@(shell eval):1:1
2022-04-11T13:39:30.122 0300 E  QUERY    [js] Error: error loading js file: get_DRMPhysicalresources_Data.js :
@(shell eval):1:1
2022-04-11T13:39:30.122 0300 E  -        [main] exiting with code -4

is there are any way to add use db2_test without break it ?

CodePudding user response:

You can try this:

 db = new Mongo().getDB("myOtherDatabase");
 

or

 db = db.getSiblingDB('myOtherDatabase')

( this is the exact js equivalent to the 'use database' helper)

docs

  • Related