3分钟后如何根据Python创建的时间在Mongodb中删除文档

时间:2018-08-15 09:53:54

标签: python python-3.x mongodb

这是我的代码:

timestamp = datetime.datetime.now()
mongo.db.user.ensure_index("createAt", expireAfterSeconds=180)
mongo.db.user.insert_one({'username':json['username'],'password':json['password'],"createAt": timestamp})

以上方法将在3分钟后删除集合中的所有文档。我想在3分钟后基于“ createAt”删除特定用户。

例如:

{ "_id" : ObjectId("5b73f30a7d1312555a4ea629"), "username" : "hanson01@gmail.com", "password" : "111111", "createAt" : ISODate("2018-08-15T09:30:00.066Z") }
{ "_id" : ObjectId("5b73f30a7d131255asdasdas"), "username" : "hanson02@gmail.com", "password" : "111111", "createAt" : ISODate("2018-08-15T09:31:00.066Z") }

用户名hanson01@gmail.com的帐户将在hanson02@gmail.com之前删除

有人有什么想法吗? 谢谢。

2 个答案:

答案 0 :(得分:3)

看看this

示例:

# First set an index on the property "expire_at", with expireAfterSeconds to 0.
mongo.db.user.ensure_index("expire_at", expireAfterSeconds=0)

#Then when you insert a document with the user you want to expire after 3 minutes, set the property "expire_at" to 3 mins from current time:
if(json['username'] == "expire_user"):
    mongo.db.user.insert_one({"expire_at": datetime.datetime.now() + datetime.timedelta(minutes = 3),  'username':json['username'], 'password':json['password']})

答案 1 :(得分:1)

您可能想尝试一下:

MessagesDisplayDelegate

有关更多选项,建议您阅读此手册: https://docs.mongodb.com/manual/tutorial/expire-data/

它们涵盖了一些不错的选择...