TTL Index in mongodb

64 views
Skip to first unread message

Sri Hari

unread,
Feb 10, 2020, 2:26:27 PM2/10/20
to mongodb-user
Hi,

We have more than 100000 documents in collections now we need drop some documents by ttl index or automatically script , please let me know how to ttl index created
We do not have timestamp field in collections

Example: fields: firstnam,last name, address, zip salary etc...

Prasad Saya

unread,
Feb 10, 2020, 8:19:16 PM2/10/20
to mongodb-user
Hello Sri Hari,

"we need drop some documents by ttl index or automatically script...": Please tell what is the criteria (or on what basis) to drop the documents in the collection.

- Prasad.

Stennie

unread,
Feb 10, 2020, 10:44:33 PM2/10/20
to mongodb-user
Hi,

A Time-To-Live (TTL) index expires documents based on an indexed date field. If you don't have a date field in your documents, you would have to add one in order to use the built-in TTL support.

If you want to remove documents based on some other criteria, you could write a program/script and schedule this to run periodically using a tool in your O/S (for example, cron in Linux).

Regards,
Stennie

Sri Hari

unread,
Feb 10, 2020, 11:56:53 PM2/10/20
to mongodb-user
Hi,
Thanks for replying Prasad and Stennie.

Can you please provide me how to add date field order wise. Those documents when it was created.

1) can you please send me automatically script with sample script for drop documents
2) how do we know each documents when insert and if it is possible which user was created those documents , here we have more than 300000 documents, multiple databases.

Prasad Saya

unread,
Feb 11, 2020, 12:43:55 AM2/11/20
to mongodb-user
Hello Sri Hari,

2) how do we know each documents when insert and if it is possible which user was created those documents , here we have more than 300000 documents, multiple databases.

If you are using the ObjectId for the document's mandatory  _id field, you can get the timestamp (date of creation) of the document from the ObjectId (See doc on ObjectId's method getTimestamp()).

You can build an update query to update the documents in your collections with a new field (the timestamp extracted from the ObjectId). Then run a delete query to delete documents based on the timestamp.

- Prasad.

Sri Hari

unread,
Feb 11, 2020, 1:22:30 AM2/11/20
to mongodb-user
Hi Prasad,

Single documents get it date by using getTimestamp command but how do I get all documents when created if I am using by this command getTimestamp this using one each documents , if it possible script or simple method all documents get it date

Prasad Saya

unread,
Feb 11, 2020, 1:53:52 AM2/11/20
to mongodb-user
Hello Sri Hari,

Here is a recent post from StackOverflow on How to add createAt field into Mongodb using _id as timestamp. I think you can use it for your need.

- Prasad.
Reply all
Reply to author
Forward
0 new messages