I need to execute a command on a remote MongoDB server, using variables declared on the shell script.


ssh root@ "mongo mydb --host --port 27017 -u user -p password --authenticationDatabase admin --eval 'db.mycollection.update({}, {$push: {'"$ENTITY"': NumberInt('"$CODE"')}})' --quiet"

Note that if I use the command outside the shell script, substituting the variables, a bash -c syntax error comes up. Example:

ssh root@ "mongo mydb --host --port 27017 -u user -p password --authenticationDatabase admin --eval 'db.mycollection.update({}, {$push: {foo: NumberInt(123)}})' --quiet"

bash: -c: line 0: syntax error near unexpected token `('

It's working now! Solution:

DBUPDATE="db.mycollection.update({}, {\$push: {${ENTITY}: NumberInt(${CODE})}})"

ssh root@ mongo mydb --host --port 27017 -u user -p password --authenticationDatabase admin --eval "'$DBUPDATE'" --quiet

closed as unclear what you're asking by Scott, Anthon, sebasth, Stephen Rauch, GAD3R Oct 12 '17 at 0:13

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • What does the command return? – Hunter.S.Thompson Oct 11 '17 at 16:16
  • It returns an error from MongoDB: SyntaxError: invalid property id @(shell eval). – Daniel Pinto Oct 11 '17 at 16:39
  • What are the contents of your variables? – sebasth Oct 11 '17 at 21:10
  • @sebasth those variables are arguments of the script (e.g. test.sh foo 123). Note that the mongo command works as intended, just not working when I use it with ssh due to the quotes. – Daniel Pinto Oct 11 '17 at 23:13
  • Put the shell commands in a script on the remote host and call that script through SSH. – Kusalananda Oct 12 '17 at 11:12
ssh root@ 'mongo mydb --host --port 27017 -u user -p password --authenticationDatabase admin --eval "db.mycollection.update({}, {$push: {'"$ENTITY"': NumberInt('"$CODE"')}})" --quiet'

I switched the double quotes with single quotes at the beginning and end and put your --eval input in double quotes.

  • It returns the same error: SyntaxError: invalid property id @(shell eval) – Daniel Pinto Oct 11 '17 at 17:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.