Reputation: 23
I am trying to execute a bash shell that calls the mongo shell with a command created dynamically. The bash shell looks like this:
#!/bin/bash
TODAY=`date '+%Y-%m-%d'`
CMD=" 'printjson(db.collection.aggregate([{$match:{processedtime:{$gte:\"$TODAY"}}},{$project:{_id:$field",count:{$sum:1}}}]))'"
echo "CMD: $CMD"
mongo host/mdb --eval $CMD
Note the processedtime field in the collection is a sting value formatted as an ISODate object.
When executed as a bash shell I get an "Unexpected token ILLEGAL" error. If I execute the command echoed to the screen I get the desired results.
My question is, Is there a way to pass in shell defined variables into the mongo shell and if there is what do I need to change to do this?
Upvotes: 1
Views: 2003
Reputation: 247012
You're note escaping enough, and I believe you don't want the literal single quotes:
CMD="printjson(db.collection.aggregate([{\$match:{processedtime:{\$gte:\"$TODAY\"}}},{\$project:{_id:\$field",count:{\$sum:1}}}]))"
# ...^.. single quote unneeded ..........^.......................^.....^.......&......^..............^...............^............^
mongo host/mdb --eval "$CMD"
# ....................^....^ crucial double quotes here
Upvotes: 2