Han Van Pham
Han Van Pham

Reputation: 490

How to delete the document in Mongodb after 3 mins based on created time by Python

This is my code:

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

This above way deletes all the documents in the collection after 3 mins. I want to delete the specific user after 3 mins based on "createAt".

Ex:

{ "_id" : ObjectId("5b73f30a7d1312555a4ea629"), "username" : "[email protected]", "password" : "111111", "createAt" : ISODate("2018-08-15T09:30:00.066Z") }
{ "_id" : ObjectId("5b73f30a7d131255asdasdas"), "username" : "[email protected]", "password" : "111111", "createAt" : ISODate("2018-08-15T09:31:00.066Z") }

The account with username [email protected] will be deleted before [email protected]

Does anyone have any ideas? Thank you.

Upvotes: 2

Views: 2310

Answers (2)

AvrahamL
AvrahamL

Reputation: 301

You may wanna try this one:

mongo.db.user.createIndex( { "expireAt": 1 }, { expireAfterSeconds: 0 })

mongo.db.user.insert_one(
        {
           "username":json['username'],
           "password":json['password'],
           "createAt": timestamp,
           "expireAt": timestamp + datetime.timedelta(0,3) //Add 3 minuets
        })

For more options, I suggest you check this manual: https://docs.mongodb.com/manual/tutorial/expire-data/

They cover some good options...

Upvotes: 1

Deepak Saini
Deepak Saini

Reputation: 2910

Look at this.

Example:

# 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']})

Upvotes: 3

Related Questions