问题
I am working on MongoDB Collections
. I have a set of collections each having many documents. I have to write a procedure to delete all those documents whose "createdDate" is older than one month from current date.
I am stuck in finding the date which is one month back of the current date in order to compare it with document's "createdDate".
Also i have to schedule this procedure, so that it can run automatically everyday. (OS is windows). How can i achieve it?
回答1:
You could try getting a date object that takes in the current date's month (bearing in mind that JavaScript month dates are 0-based index) and add 1 to get one month's date from now, which you can then use in your query with $gt
operator on the createdDate
field:
var now = new Date();
d = new Date(now.getFullYear(), now.getMonth()+1, now.getDate());
db.collection.remove({ createdDate: { $gt: d } })
UPDATE
For your second question,
i have to schedule this procedure, so that it can run automatically everyday. (OS is windows). How can i achieve it?
MongoDB currently has no support for native Job scheduling. Most operating systems have a way to run scheduled programs like cron or Windows Task Scheduler etc so since this is quite a broad question, I can only suggest you write a custom shell script with the above that you can schedule with Windows Task Scheduler to run everyday.
来源:https://stackoverflow.com/questions/29127295/find-and-remove-all-documents-whose-createddate-is-one-month-older