简体   繁体   中英

Expire a document from a collection in MongoDB only if a condition is fulfilled

I've been looking how to expire documents in a MongoDB collection (I'm using mongoose and node.js) and found the TTL index option.

In my case, I don't always want to expire the documents, only conditionally if the status element inside the document has the values approved/rejected.

My use case is that I have a /proposal/1 element that will need to be approved or rejected, and in the meantime, the status inside the document has the value 'under review'. I don't want to expire the documents that have this status, but only the ones that have been approved or rejected already?

Is there some way this can be achieved through the schema or adding something extra to the document when the status is changed to approved/rejected?

Cheers, Deborah

Add another field whose value is only set for those documents you want to expire, then add a TTL index on that field.

Or, if TTL index expires documents that do not have a value in the corresponding field immediately, set the value in this new field to a time far in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM