0

So I have a mongo collection called 'abcd', inside my collection I am creating indexes called 'token'. I understand that TTL needs to be tied to a ISO datetime object in mongo as an index, or as part of an array.

I was unsuccessful at getting the token to expire when adding an index to my 'token'. So I am adding a created_timestamp ISO date object into my "data" array of my token index.

My question is, how can I use my expireAfterSeconds=10 attribute to the object of created_timestamp of my data array. My goal is to get the entire token index to delete after 10 seconds. Here is a json of what my 'token' document looks like:

{
"_id" : ObjectId("5a7dec4189284441fe9aa1fc"),
"token" : "RfAQ3W",
"data" : "{\"token\": {\"user_id\": 308, \"exp\": 151821111, \"team_code\": 1022, \"created_timestamp\": \"2018-02-09T18:45:24.823785\}}"

}

I want to be able to expire my token after 10 seconds from the created_timestamp which is the ISO date of when the token gets generated to mongodb

I am using: Pymongo 3.4 Mongoengine 0.13 Python 2.7

Masoud Mokhtari
  • 2,390
  • 1
  • 17
  • 45

1 Answers1

0

Why don't you create a new field 'created_at' with Date() value and make it TTL index instead of putting this in an array?

After all this whole document is going to delete after 10 sec.

Rakesh Gupta
  • 354
  • 4
  • 12
  • Is it possible for me to set an `expireAfterSeconds` attribute to a `collection.insert()` function? – locodev123 Feb 12 '18 at 15:46
  • According to mongo docs, i can only use that ttl feature when using `create_index()`. issue with that is my application does not use `create_index` but rather insert – locodev123 Feb 12 '18 at 15:47
  • @locodev123 You just have to create index once. Don't bother about it after that. You can insert then normally – Rakesh Gupta Feb 12 '18 at 16:09
  • when i create my index like so: `c.create_index('token', expireAfterSeconds=20)` My tokens that i am generating are not getting deleted from database after 20 seconds.. – locodev123 Feb 12 '18 at 16:52
  • Use MongoDb Compass for easy GUI interaction with your database. That is very useful – Rakesh Gupta Feb 12 '18 at 17:01
  • c is the collection object, i have this inside a conditional check, if `c = self.db.create_collection(self.collection_name)` if collection does not exists, else: `c.create_index('token', expireAfterSeconds=20)` – locodev123 Feb 12 '18 at 18:00