1

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! :)

3
  • shell variables don't get expanded in single quotes. Try enclosing your variable inside double quotes like command 'previous'"$var"'next" Commented Oct 5, 2015 at 16:55
  • Thanks @user000001! Worked as a charm, hm, dont know why I didn't try that, any idea on how I can $today as a real date value? and not as string? Like with javascript, var from = ISODate("2011-11-24") Any idea on how I can do the same in shell/bash? Commented Oct 5, 2015 at 18:59
  • I don't think that you can do that from bash. You'll probably have to do it from mongo, but I don't know how... Commented Oct 5, 2015 at 19:02

2 Answers 2

3

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

!/bin/sh

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):

!/bin/sh

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 :)

Sign up to request clarification or add additional context in comments.

Comments

0

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});"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.