0

I am trying to create TTL index to delete documents older than 30 min on "generated" field for below sample document

sample document: {"_id" : ObjectId("5850308c077b3d1ccc11cef0"), "generated" : NumberLong("1481650316760")}

Question 1)is it possible to do so as the "generated" field is not date type 2)Is there any alternative way to achieve this with out modifying the document structure

1 Answers1

0

is it possible to do so as the "generated" field is not date type

As at MongoDB 3.4, TTL indexes only support fields with BSON Date values:

If the indexed field in a document is not a date or an array that holds
date values, the document will not expire.

Is there any alternative way to achieve this with out modifying the document structure

If you want to support expiration of documents based on field types or comparisons outside of what is provided in the built-in TTL index, you can always write your own script and schedule it using something like the cron utility (Linux/Unix operating systems) or Task Scheduler (Windows).

In this case your script would remove all documents where the generated NumberLong value is older than your desired expiration cutoff (eg. 30 minutes). The query in the mongo shell would be similar to:

db.collection.remove(
    {
        generated: {
            // Expire documents older than half hour: 30 minutes * 60 seconds * 1000 ms
            $lt: (Date.now() - (30 * 60 * 1000))
        }
    }
)

You could write this in your favourite application language, pass as a .js file to the mongo shell, or pass JavaScript code to the mongo shell using --eval. For more information see Write Scripts for the mongo Shell in the MongoDB manual.

Stennie
  • 1,270
  • 7
  • 13