Reputation: 93
I don't know if this is even possible, I can see that there might be issues with using bash parameters in a mongo eval query. What I'm trying to do is to update documents in mongo where a value date is greater than todays date.
Example: Today's date is less(<) than tomorrows date, thus update field X of same document.
I've got the following, but I'm wondering how to pass the date variable to the mongo query. Is it even possible? Is there another way to Rome?
#!/bin/sh
today="$(date +'%Y-%m-%d')"
mongo db --eval 'db.Scheme.update({"FutureDate":{$gte: $today}},{$set:{"X":"$today"}});'
Alternately I've tried to switch $today with new Date().setHours(0,0,0,0) but are unable to perform the query.
Help or constructive feedback is much appreciated, thanks! :)
Upvotes: 1
Views: 3727
Reputation: 29
try following
#!/bin/bash
Value="Example"
mongo databaseurl:port/database -u username -p password --eval \
"db.Scheme.update({\"FutureDate\":{$gte: new Date()}},{$set :{\"X\":\"${Value}\"}},\{multi:true});"
Upvotes: 0
Reputation: 93
I came to a solution to my problem, it solves (I would say 95%) of my case. I found that I didn't need to pass a parameter although I was able to do it using '"$variable"' inside the mongo query while testing (see To pass variable for more).
My query solution is below (does not include passing variable):
db.Scheme.update({"FutureDate":{$gte: new Date()}},{$set :{"X":Value}},{multi:true});
{multi:true} allows all documents in Scheme to be looped.
Full query in script
mongo databaseurl:port/database -u username -p password --eval 'db.Scheme.update({"FutureDate":{$gte: new Date()}},{$set :{"X":Value}},{multi:true});'
To pass variable (example):
Value="Example"
mongo databaseurl:port/database -u username -p password --eval 'db.Scheme.update({"FutureDate":{$gte: new Date()}},{$set :{"X":'"$Value"'}},{multi:true});'
Hope it can help someone else as well! Thanks user000001 for help along the way :)
Upvotes: 3