查找并删除所有“createdDate"为大了一个月 [英] Find and remove all documents whose "createdDate" is one month older

查看:15
本文介绍了查找并删除所有“createdDate"为大了一个月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究 MongoDB Collections.我有一组集合,每个集合都有许多文档.我必须编写一个程序来删除所有那些createdDate"比当前日期早一个月的文档.

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.

我一直在寻找距当前日期早一个月的日期,以便将其与文档的createdDate"进行比较.

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".

此外,我必须安排此程序,以便它每天都能自动运行.(操作系统是 Windows).我怎样才能实现它?

Also i have to schedule this procedure, so that it can run automatically everyday. (OS is windows). How can i achieve it?

推荐答案

您可以尝试获取一个包含当前日期月份的日期对象(请记住 JavaScript 月份日期是基于 0 的索引)并添加 1 以获得从现在起一个月的日期,然后您可以在您的查询中使用 createdDate 字段上的 $gt 运算符:

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

更新

对于你的第二个问题,

我必须安排这个程序,以便它可以自动运行每天.(操作系统是 Windows).我怎样才能实现它?

i have to schedule this procedure, so that it can run automatically everyday. (OS is windows). How can i achieve it?

MongoDB 目前不支持原生作业调度.大多数操作系统都有运行计划程序的方法,如 cron 或 Windows 任务计划程序等,因此由于这是一个相当广泛的问题,我只能建议您使用上述内容编写自定义 shell 脚本,您可以使用 Windows 任务计划程序安排每天运行.

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.

这篇关于查找并删除所有“createdDate"为大了一个月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆