Is there a way to use shell variables in a MongoDB query?
I have this for example:
#!/usr/bin/env bash
mongo --eval "use cdt_db; db.users.update({username:'${USER}'}, {'\$set':{roles:['Admin']}});"
I tried single quotes and double quotes, I get this error:
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.9
2017-10-09T13:53:51.747-0700 E QUERY [thread1] SyntaxError: missing ; before statement @(shell eval):1:4
$setbe without the quotes? The safest way would be to write the expression under single quotes, concatenating it with variable values:mongo cdt_db --eval 'db.users.update({username:"'"$USER"'"}, {$set:{roles:["Admin"]}});'.mongo cdt_db --eval 'db.users.update({username:"'${USER}'"}, {$set:{roles:["Admin"]}});'$USERundergoes a shell parameter expansion (always, unless single-quoted). So ifUSER='*', then"$USER"will expand to*. However, if you don't double-quote it then it also goes through a pathname expansion (globbing), so$USERwill expand tofile1 file2 .... If you writecmd 'str' $USER, the variable is pathname-expanded (cmdreceivesstr file1 file2 ...), but if you writecmd 'str'$USER, then the variable is not pathname-expanded (unless has spaces), but spaces inUSERare not preserved! So the safe thing is to writecmd 'str'"$USER".