如何用Python从MongoDB获取24小时前的记录?

0 投票
1 回答
918 浏览
提问于 2025-04-18 10:02

我需要从我的mongodb数据库中删除那些在当前时间之前24小时就已经存在的记录。我有这样的记录:

{
"_id" : ObjectId("53993f67ccbc960c7d05b74d"),
"userName" : "krishna",
"countryCode" : "91",
"countryName" : "India",
"mobileNumber" : "99143xxxxx",
"name" : "Krishna",
"password" : "aXRvbkAxMjM=",
"registeredOn" : ISODate("2014-06-12T05:49:27.970Z"),

}
{
"_id" : ObjectId("53993f67ccbc960c7d05b74e"),
"userName" : "mulagala",
"countryCode" : "91",
"countryName" : "India",
"mobileNumber" : "99122xxxxx",
"name" : "Krishna",
"password" : "aXRvbkAxMjM=",
"registeredOn" : ISODate("2014-06-16T05:49:27.970Z"),

}

现在我想删除那些在当前时间之前24小时注册的记录。请问我该如何用Python来删除它们呢?谢谢!

1 个回答

2

你可以通过定期运行一个查询来解决这个问题:

collection.remove({ 
    'registeredOn': { '$lte': datetime.now() - timedelta( hours=24 ) }
})

或者你可以看看 TTL 索引。MongoDB 服务器会每隔几分钟自动检查这些索引,你不需要额外编写代码:

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

所以如果这个方法对你有用,并且你不需要手动控制的话,这可能是一个很好的解决方案,适合你的应用。

撰写回答