2

I wrote a shell script to create a data dump of records updated yesterday using mongoexport command.

yesterday=$(date -d 'yesterday 00:00:00' '+%s'000)
today=$(date -d 'today 00:00:00' '+%s'000)
query="'{\"updated_at\":{\$gte:new Date(${yesterday}),\$lte:new Date(${today})}}'"
echo ${query}

mongoexport -h $HOST -d $DOC -c $COL_NAME -u $USER -p $PWD -q ${query} -o $fileName

After adding query, when I run the shell script I get below error in console

'{"updated_at":{$gte:new Date(1484287200000),$lte:new Date(1484373600000)}}'
too many positional arguments: [Date(1484287200000),$lte:new Date(1484373600000)}}']
try 'mongoexport --help' for more information

When I run this query in command line it works properly. Can someone pls let me know why is this error when ran in shell script?

This works in command line.

$mongoexport -h <<HOST>> -d <<DOC>> -c <<COL> -u <<UN>> -p <<PWD>> -q '{"updated_at":{"$gte":new Date(1484287200000),"$lte":new Date(1484373600000)}}'

2 Answers 2

1

There is a rule of thumb in bash: when you use a variable, always surround it with double quotes. There are exceptions, but they are rare.

mongoexport -h "$HOST" -d "$DOC" -c "$COL_NAME" -u "$USER" -p "$PWD" -q "${query}" -o "$fileName"
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply. When I tried in shell script with double quotes, I get below error. '{"updated_at":{$gte:new Date(1484287200000),$lte:new Date(1484373600000)}}' 2017-01-14T18:02:22.557-0600 error validating settings: query '[39 123 34 117 112 100 97 116 101 100 95 97 116 34 58 123 36 103 116 101 58 110 101 119 32 68 97 116 101 40 49 52 56 52 50 56 55 50 48 48 48 48 48 41 44 36 108 116 101 58 110 101 119 32 68 97 116 101 40 49 52 56 52 51 55 51 54 48 48 48 48 48 41 125 125 39]' is not valid JSON: json: cannot unmarshal string into Go value of type map[string]interface {}
@user1637487 I don't know mongo but I believe the surrounding single quotes, in your definition of query should be remove. Keep only the double quotes: query="{...}"
0

This code worked for me

yesterday=$(date -d 'yesterday 00:00:00' '+%s'000)
today=$(date -d 'today 00:00:00' '+%s'000)
query1="{\"transactionDate\":{\$gte: new Date(${yesterday}),\$lte: new Date(${today})}}"
echo $yesterday
echo $today

mongoexport -d databasename-c collectionname --host yourip --port 27017 -p password -u username-q "${query1}" --type=csv --fields=transactionDate,amount > test5.csv

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.