How to execute mongo commands from bash?

后端 未结 3 2007
时光说笑
时光说笑 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:41

    From the mongo docs:

    --eval option

    Use the --eval option to mongo to pass the shell a JavaScript fragment, as in the following: mongo test --eval "printjson(db.getCollectionNames())"

    You can also put your JS Fragments into a .js file then do:

    mongo < myScript.js
    

    You may also find more useful stuff in this SO question

    0 讨论(0)
  • 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()"
    
    0 讨论(0)
  • 2021-02-19 18:47

    You can use heredoc syntax.

    #! /bin/sh
    mongo <<EOF
    use admin
    db.shutdownServer()
    quit()
    exit
    

    Turns out heredoc syntax throws a warning when EOF is missing at the end for bash script. This is the bash script version.

    #! /bin/bash
    mongo <<EOF
    use admin
    db.shutdownServer()
    quit()
    EOF
    

    Here is the output, I guess this is what you expected.

    MongoDB shell version: 2.4.14
    connecting to: test
    switched to db admin
    Wed Jun 24 17:07:23.808 DBClientCursor::init call() failed
    server should be down...
    Wed Jun 24 17:07:23.810 trying reconnect to 127.0.0.1:27017
    Wed Jun 24 17:07:23.810 reconnect 127.0.0.1:27017 ok
    Wed Jun 24 17:07:23.812 Socket recv() errno:104 Connection reset by peer 127.0.0.1:27017
    Wed Jun 24 17:07:23.812 SocketException: remote: 127.0.0.1:27017 error: 9001 socket exception [RECV_ERROR] server [127.0.0.1:27017] 
    Wed Jun 24 17:07:23.812 DBClientCursor::init call() failed
    
    0 讨论(0)
提交回复
热议问题