From ded981b80d1a3685063de68d5083ac7640621f08 Mon Sep 17 00:00:00 2001 From: Sanjiban Sengupta Date: Thu, 22 Feb 2024 17:18:34 +0530 Subject: [PATCH] feat: ttl index in mongodb collections (#87) --- api/components/shareable.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/api/components/shareable.py b/api/components/shareable.py index 9c26e14d..992a3524 100644 --- a/api/components/shareable.py +++ b/api/components/shareable.py @@ -1,8 +1,10 @@ +from datetime import datetime import os from bson.objectid import ObjectId from motor.motor_asyncio import AsyncIOMotorClient from pydantic import BaseModel +from pymongo import ASCENDING DEFAULT_MONGO_URL = "mongodb://localhost:27017" @@ -27,6 +29,10 @@ def __init__(self): def initialize(self): database = self.client["plans"] collection = database["links"] + + # TTL index in the createdAt field to expire record after a week + collection.create_index([("createdAt", ASCENDING)], expireAfterSeconds=604800) + return collection async def get_record(self, collection, id): @@ -37,6 +43,7 @@ async def add_record(self, collection, data): data = { "json_string": data.json_string, "validator_overrides": data.validator_overrides, + "createdAt": datetime.utcnow() } result = await collection.insert_one(data) return str(result.inserted_id)