4

Here is an example query:

db.readings.find( {"_id.s" : ISODate("2012-11-01T00:05:00Z") } ).count()

Query works in the mongo shell. However, in a bash script or directly in the Ubuntu shell

mongo fivemin --eval "printjson(db.readings.find( {"_id.s" : ISODate("2012-11-01T00:05:00Z") } ).count())"

returns a SyntaxError: missing : after property id (shell eval):1

I can't seem to find a problem with the query. I reverted to { "_id" : {"s" : ...} }, and it still gives the same problem. find().count() works however.

5 Answers 5

5

Had the same issue in bash shell.

This will fail because of double quotes:

mongo fivemin --eval "printjson(db.readings.find( {"_id.s" : ISODate("2012-11-01T00:05:00Z") } ).count())"

But using the eval string in single quote it works:

mongo fivemin --eval 'printjson(db.readings.find( {"_id.s" : ISODate("2012-11-01T00:05:00Z") } ).count())'

And if you use a $ sign like $regex you need to escape it:

mongo fivemin --eval 'printjson(db.readings.find( {"_id.s" : {"\$regex":"2012-11-01T*"} } ).count())'
1

use single quotes into double,

e.g.:

mongo fivemin --eval "printjson(db.readings.find( {'_id.s' : ISODate('2012-11-01T00:05:00Z') } ).count())"
0

There is also another possible issue using --eval with bash double quotes, if the query contains mongo operators i.e. $ne, $gt etc, since operators start with $.

double quotes:

$ echo " '$ne': null "
$ => '': null

single quotes:

$ echo ' "$ne": null '
$ => "$ne": null

Bash tries to replace these operators with variables.

$ ne = 'test'
$ echo " '$ne': null "
$ => 'test': null

So, I always recommend to use --eval with single quotes.

0

Just sat and thought about it. It seems to be a problem with bash exiting out on the " (should have noticed immediately!). Instead I used ' (or I guess you can use /" for JSON) so the query looks like:

printjson(db.readings.find({'_id.s' : ISODate('2013-01-01T00:05:00Z') }).count())"

0

The best way to handle this is to build the mongo command in a var. Then use eval command to execute the mongo command:

mongo_update_query="db.collectionName.update({ name:\""${some_name}"\", \
{ \$addToSet: { nick_names : { \$each : [ ${name_array} ] }}});"

mongo_cmd_str=$(echo "mongo --host ${mongo_host} --port ${mongo_port} ${mongo_database} --eval '${mongo_update_query}'")

# the actual call to mongo query
eval ${mongo_cmd_str}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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