Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expire index in mongoDB based on condition

I have boolean field named pending in Mongoengine model in Python. I want the document to be removed after 1 hour only if pending=True. If I needed to remove the document after 1 hour unconditionally I would just set expire index. Is there some smart and easy way to add some conditional check to expire index?

Thank you in advance!

like image 824
giliev Avatar asked Dec 14 '22 04:12

giliev


1 Answers

Since MongoDB version 3.2 you can use Partial Indexes (in conjunction with TTL Indexes).

This index will remove all documents that had pending = true for 1 hour. If within this hour a document is updated and no longer pending, it will not be removed.

let keys = { lastModifiedDate: -1 };
let options = { 
    expireAfterSeconds: 3600, 
    partialFilterExpression: { pending: true }
};
db.getCollection("collection").createIndex(keys, options);

(Although this answer is probably no longer relevant to you, I'm sure someone else will find it useful in the future)

like image 125
Dušan Brejka Avatar answered Dec 27 '22 00:12

Dušan Brejka