MongoDB 查询超过 30 秒的文档 [英] MongoDB query for document older than 30 seconds
问题描述
有没有人有一个很好的方法来查询超过 30 秒的文档集合.我正在创建一个清理工作者,在项目处于特定状态超过 30 秒后将项目标记为失败.
Does anyone have a good approach for a query against a collection for documents that are older than 30 seconds. I'm creating a cleanup worker that marks items as failed after they have been in a specific state for more than 30 seconds.
这并不重要,但我正在使用 mongojs 来解决这个问题.
Not that it matters, but I'm using mongojs for this one.
每个文档都有一个创建
时间与之关联.
Every document has a created
time associated with it.
推荐答案
我们假设您的文档中有一个 created_at
或类似字段,该字段具有插入或以其他方式修改的时间,具体取决于哪个对你很重要.
We are assuming you have a created_at
or similar field in your document that has the time it was inserted or otherwise modified depending on which is important to you.
您可能想查看 update 将您的更改应用到与您的查询匹配的所有文档.设置你想看过去的时间应该相当简单
Rather than iterate over the results you might want to look at the multi
option in update to apply your change to all documents that match your query. Setting the time you want to look past should be fairly straightforward
在 shell 语法中,这应该与驱动程序几乎相同:
In shell syntax, which should be pretty much the same of the driver:
db.collection.update({
created_at: {$lt: time },
state: oldstate
},
{$set: { state: newstate } }, false, true )
第一个 false
用于更新插入,在此用法中没有任何意义,第二个 true
标记用于 multi
文档更新.
The first false
being for upserts which does not make any sense in this usage and the second true
marking for multi
document update.
如果这些文件确实是短暂的,并且之后您不再需要它们,那么您可以考虑 上限集合.您可以为这些设置总大小
或生存时间
选项,并且自然插入顺序有利于处理排队条目.
If the documents are indeed going to be short lived and you have no other need for them afterwards, then you might consider capped collections. You can have a total size
or time to live
option for these and the natural insertion order favours processing of queued entries.
这篇关于MongoDB 查询超过 30 秒的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!