How to create TTL Index on long timestamp in MongoDB
Asked Answered
M

2

8

In my mongo database I have field timestamp which holds time of creation in timestamp ie: "timestamp": 1544029233021 I want to create TTL index on this field, but in docs example is done on "createdAt": new Date(), which is ISODate("2018-12-13T17:00:10.433Z")

Is it possible to in any way to make TTL Index work on timestamp field?

Because this doesnt work:

db.coll.createIndex( { "timestamp": 1 }, { expireAfterSeconds: 3600 } )
Manet answered 13/12, 2018 at 17:2 Comment(0)
P
14

The documents aren't being expired because the timestamp value is an integer.

TTL indexes will only work on documents where the indexed field is a Date or holds an array of Dates:

If the indexed field in a document is not a date or an array that holds a date value(s), the document will not expire.

(https://docs.mongodb.com/manual/core/index-ttl/#expiration-of-data)

Photoreconnaissance answered 13/12, 2018 at 23:31 Comment(0)
V
0

Yes, MongoDB supports TTL indexes on fields containing epoch time, represented as long integers.

You can create a TTL index on a field containing epoch time directly without needing to convert it to a date object. It must be there in newer versions of MongoDB.

Vacation answered 13/3 at 12:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.