简体   繁体   English

如果当前日期>文档日期,如何删除文档

[英]How delete a document if the current date > document date

I have the following schema: 我有以下架构:

Schema = {(
   name: String,
   age: Number,
   email: String,
   date: {
     type: Date
   }
)};

And i am inserting data in my db dinamically throw a form and a post route. 而且我正在数据库中插入数据,然后抛出一个表单和一个发布路由。 After that, i am pulling this data and showing in the html using ejs view engine. 之后,我将提取此数据并使用ejs视图引擎在html中显示。

The problem is that i want delete documents who have the date field less than the current date. 问题是我想删除日期字段小于当前日期的文档。

I was trying to use TTL , but i don't know exactly how implement, should i use in the schema, or before save the data, in a new entry? 我试图使用TTL ,但是我不知道确切地如何实现,应该在架构中使用还是在保存数据之前在新条目中使用?

For example, in my post route i have the following code: 例如,在我的张贴路线中,我有以下代码:

var new = new Schema({
   name: req.body.name,
   age: req.body.age,
   email: req.body.email,
   date: {
     type: req.body.date
   }
});

new.save...... 
.... etc

I want delete this document 24 hours after the req.body.date, and no 24 after created... 我想在req.body.date之后24小时删除此文档,而在创建之后再删除24 ...

I'm little confuse, any help is very welcome. 我有点困惑,非常感谢您的帮助。

You can achieve this with a TTL collection . 您可以通过TTL收集来实现。

You could set the expireAfterSeconds to 86400 and set the date element to the current date and it should expire after a full day. 您可以将expireAfterSeconds设置为86400并将date元素设置为当前日期,并且它应该在一整天后过期。

The way this would be implemented is that while connected to the server you would issue this command: 实现的方式是,在连接到服务器时,您将发出以下命令:

db.collection.ensureIndex( { "date.type": 1 }, { expireAfterSeconds: 86400 } )

I don't know how your application sends what data it sends to MongoDB, but you'll want to make sure that it is sending a timestamp corresponding to the midnight before the current time. 我不知道您的应用程序如何将其发送的数据发送到MongoDB,但是您需要确保它正在发送与当前时间之前的午夜相对应的时间戳。

For example if it is 1/29/2015 at 2:07:33 PM when the form is sent, the timestamp sent to MongoDB should be 1/29/2015 12:00:00 AM. 例如,如果发送表单时是2015年1月29日下午2:07:33,则发送到MongoDB的时间戳应该为2015年1月29日12:00:00 AM。 With the index set above, MongoDB will remove the document at 1/30/2015 at 12:00:00 AM. 使用上面设置的索引,MongoDB将在2015年1月30日上午12:00:00删除文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM