Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute mongo commands through shell scripts?

I want to execute mongo commands in shell script, e.g. in a script test.sh:

#!/bin/sh mongo myDbName db.mycollection.findOne() show collections 

When I execute this script via ./test.sh, then the connection to MongoDB is established, but the following commands are not executed.

How to execute other commands through shell script test.sh?

like image 908
StackOverFlow Avatar asked Jan 29 '11 15:01

StackOverFlow


People also ask

Which command is used to launch the mongo shell?

Connect to MongoDB database You can start the server in CMD using the following command. Then type mongo command to run the shell. Now you are in the Mongo shell. If you want, you can run the mongo and mongod without the command prompt.


1 Answers

You can also evaluate a command using the --eval flag, if it is just a single command.

mongo --eval "printjson(db.serverStatus())" 

Please note: if you are using Mongo operators, starting with a $ sign, you'll want to surround the eval argument in single quotes to keep the shell from evaluating the operator as an environment variable:

mongo --eval 'db.mycollection.update({"name":"foo"},{$set:{"this":"that"}});' myDbName 

Otherwise you may see something like this:

mongo --eval "db.test.update({\"name\":\"foo\"},{$set:{\"this\":\"that\"}});" > E QUERY    SyntaxError: Unexpected token : 
like image 171
theTuxRacer Avatar answered Sep 21 '22 21:09

theTuxRacer