0

I have created a CRON job that takes backup of database everyday.

The script has a command of Mongodump with a condition to dump the records that are 7 days old.

The script runs fine until I added the --query parameter into the mongodump command.

mongodump [host, port and dbparams] --query "{_id: {\$lt: ObjectId(Math.floor(new Date(Date.now() - 86400000*7)/1000).toString(16) + '0000000000000000')}}" 

An error thrown because of the --query, which says:

assertion: 16619 code FailedToParse: FailedToParse: Expecting quoted string: offset:21

So what is the correct way to integrate this query into the script?

3
  • Does using '$lt' instead of \$lt help? Commented Nov 1, 2013 at 12:55
  • @OneOfOne Nope, the '$lt' without '\' gives error 'First character in field must be [A-Za-z$_]: offset:7'. I have added '\' to escape the $ . Commented Nov 1, 2013 at 13:07
  • @sohelkhalifa can we run the scripts without having mongo shell installed in machine? Commented Aug 21, 2021 at 6:35

1 Answer 1

2

You could compute the date string using the shell and then pass that into the --query option. Here is your original Javascript expression and the equivalent computation in the shell:

$ mongo --eval "Math.floor(new Date(Date.now() - 86400000*7)/1000).toString(16) + '0000000000000000'"
526a7ac00000000000000000
$ printf '%x0000000000000000' $(($(date +%s) - 86400*7))
526a7ac00000000000000000

You would then use this in a short script such as the following:

now=$(printf '%x0000000000000000' $(($(date +%s) - 86400*7)))
mongodump --query "{_id: {\$lt: '$now'}}"

Hope this helps,

Bruce

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

2 Comments

Bruce's solution, a little simpler: printf '%x0000000000000000' $(date --date='7 days ago' +%s)
Good improvement Rafa.

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.