2

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

The account with username hanson01@gmail.com will be deleted before hanson02@gmail.com

Does anyone have any ideas? Thank you.

Han Van Pham
  • 462
  • 1
  • 6
  • 24
  • What do you mean `Just deletes all documents after 3 mins` https://stackoverflow.com/questions/20431833/mongodb-ttl-expires-documents-early could change to datetime.datetime.utcnow() anyway the ensure index deprecated, change to create_index then) – Phung Duy Phong Aug 15 '18 at 10:11
  • Accept the ans if it solved your issue. Thanks. – Deepak Saini Aug 15 '18 at 11:29
  • "Just deletes all documents after 3 mins" ý mình là cái cách trên chỉ xóa hết documents trong collection sau 3 phút chứ k phải xóa từng thằng theo thứ tự. @PhungDuyPhong – Han Van Pham Aug 16 '18 at 02:00

2 Answers2

3

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']})
Deepak Saini
  • 2,810
  • 1
  • 19
  • 26
1

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...

AvrahamL
  • 181
  • 4
  • 16