0

I have a shell script with a query to get some information in a MongoDB database and I'm having a problem to make a more detailed query.

For example, if the query is simple it works, like this:

exec_mongo='mongo -u USER HOST/MYDATABASE -pPASSWORD --authenticationDatabase admin'

query='printjson(db.MYDATABASE.find().toArray())'

res=$($exec_mongo --eval $query)

echo $res >> results.csv

But, if I add some parameters, like "AND" or "OR", doesn't work:

exec_mongo='mongo -u USER HOST/MYDATABASE -pPASSWORD --authenticationDatabase admin'

query='printjson(db.MYDATABASE.find($and: [ {DATE:"2018"}, {NAME:"TEST"} ]).toArray())'

res=$($exec_mongo --eval $query)

echo $res >> results.csv

I think maybe this is because of the $and, but not sure about. Can anyone help me with this, please?

Note: the code above works if I type directly in mongodb access (mongo shell).

Thanks in advance.

noob
  • 774
  • 1
  • 10
  • 23
Rffonseca
  • 29
  • 1
  • 6

1 Answers1

0

In bash and sh certain characters need escaping. You need to also use " and NOT '. Please see here for an answer as to what the difference is.

Within your script; $ [ { all need escaping with a \ before them.

query="printjson(db.MYDATABASE.find( \$and: \[ \{ DATE:"2018" \}, \{ NAME:"TEST" \} \])"
  • Thanks for the tip. I forgot to escape `[ ] { }`. But stiil not working after escape them. What can be now? – Rffonseca Feb 14 '18 at 14:28
  • It returns me this error: `SyntaxError: Unexpected token ILLEGAL` – Rffonseca Feb 14 '18 at 14:29
  • `query='printjson(db.MYDATABASE.find(\{\$and:\[\{DATE:"2018"\},\{NAME:"TEST"\},\{\$or:\[\{CITY:"MYCITY"\},\{CITY:"ANOTHERCITY"\}\]\}\]\}));'` Putting a SQL query for the same situation to you understand better what I'm trying to get: `SELECT * FROM MYTABLE WHERE DATE = "2018" AND NAME = "TEST" AND CITY IN ("MYCITY","CITY")` – Rffonseca Feb 14 '18 at 15:50
  • @Rffonseca, sorry your comment is a little confusing! Did using `"` not help? –  Feb 14 '18 at 15:59
  • I find in web some codes including the `toArray()` function at end of expression and works (and without escaping) :) `query='printjson(db.MYDATABASE.find({$and:[{DATE:"2018"},{NAME:"TEST"},{$or:[{CITY:"MYCITY"},{CITY:"ANOTHERCITY"}]}]}).toArray());'` But with this I just have one situation: it returns like the `pretty()` code, so print in json format. Have you any idea how I can print one result per line? – Rffonseca Feb 14 '18 at 16:03