Set different expiry time for individual documents in mongodb

1,926 views
Skip to first unread message

sarvesh gupta

unread,
Jul 31, 2013, 3:27:08 AM7/31/13
to mongo...@googlegroups.com
Hi All,

I am using Mongo 2.4.5 and writing code using C# driver.

I found that we can we only set expiry time at collection level. As per my use case, I require to set a different ttl for individual document.

Please advise.

Regards,
Sarvesh

Derick Rethans

unread,
Jul 31, 2013, 10:12:01 AM7/31/13
to mongo...@googlegroups.com
On Wed, 31 Jul 2013, sarvesh gupta wrote:

> I am using Mongo 2.4.5 and writing code using C# driver.
>
> I found that we can we only set expiry time at collection level. As
> per my use case, I require to set a different ttl for individual
> document.

As the TTL expiry happens on a check for a specific field's date/time,
plus the ttl that is set in the index, you can of course precalculate
the field's date value... so you could just add the TTL to the field's
value, and set a TTL of 0:

Instead of:

TTL: dateValue = 60;

{
_id: 42;
dateValue: new ISODate( "2013-07-31 15:10:41" );
}

You can do:

TTL: dateValue = 0;

{
_id: 42;
dateValue: new ISODate( "2013-07-31 15:11:41" );
}


I.e. = add the 60 to the `dateValue` field. With this, you can then add
different ttls for each document yourself.

cheers,
Derick

--
{
website: [ "http://mongodb.org", "http://derickrethans.nl" ],
twitter: [ "@derickr", "@mongodb" ]
}

Asya Kamsky

unread,
Jul 31, 2013, 1:16:00 PM7/31/13
to mongo...@googlegroups.com
In addition to what Derick said, it may be helpful to remember that
while the "expires after X seconds" value is collection-wide, the
field that is being indexed will be different in every document. So
it's always up to you (the application) to set that field accordingly
for each document.

By the way, this type of question should probably be sent to
mongodb-users Google Group, since mongodb-dev is for developers of the
actual MongoDB kernel, rather than developers who use MongoDB in their
application.

Asya
> --
> You received this message because you are subscribed to the Google Groups
> "mongodb-dev" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to mongodb-dev...@googlegroups.com.
> To post to this group, send email to mongo...@googlegroups.com.
> Visit this group at http://groups.google.com/group/mongodb-dev.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>

sarvesh gupta

unread,
Aug 1, 2013, 9:17:49 AM8/1/13
to mongo...@googlegroups.com
Thanks a lot Derick. It surely helps.

Regards,
Sarvesh

sarvesh gupta

unread,
Aug 1, 2013, 9:19:22 AM8/1/13
to mongo...@googlegroups.com
Thanks a lot Asya. Sorry for the wrong placement of question.It was unintentional but I will keep it mind in future.

Regards,
Sarvesh
Reply all
Reply to author
Forward
0 new messages