Find and remove all documents whose “createdDate” is one month older

二次信任 提交于 2019-12-20 01:58:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!