Mongo query works in mongo shell but not in a bash mongo --eval?

mongodb

Solution

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())'

Problem

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.

Original source