How to execute mongo commands from bash?

后端 未结 3 2008
时光说笑
时光说笑 2021-02-19 18:04

I am trying to run this command from bash script:

 mongo 192.168.10.20:27000 --eval \"use admin && db.shutdownServer() && quit()\"
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-19 18:44

    There are differences between interactive & scripted mongo shell sessions. In particular, commands like use admin are not valid JavaScript and will only work in an interactive shell session.

    The working equivalent of your shutdown command line would be:

    mongo 192.168.10.20:27000/admin --eval "db.shutdownServer()"
    

    You can include the database to use in the connection string, and there is no need to quit from a scripted mongo shell session.

    If you do need to change databases from a scripted session, there is a db.getSiblingDB() JavaScript function. An alternative way to write the shutdown command above would be:

     mongo 192.168.10.20:27000 --eval "db=db.getSiblingDB('admin');db.shutdownServer()"
    

提交回复
热议问题