Reactivemongo TTL collections

920 views Asked by At

I know I can set TTL in MongoDB with

db.ttl_collection.ensureIndex( { "Date": 1 }, { expireAfterSeconds: 10 } ) 

and I know I can ensure index with Scala in Reactivemongo with

collection.indexesManager.ensure(index)

But how can I set TTL collections in reactivemongo from code? Or is there any other way to make expiring records in Mongo with reactivemongo in Scala?

2

There are 2 answers

1
Krzysztof Wende On

I finally found it out. It's not really clear way to do it but seems to work:

collection.indexesManager.ensure(Index(Seq(("Date", IndexType(BSONInteger(1)))), Some("expireAfterSeconds"), false, false, false, false, None, BSONDocument( "expireAfterSeconds" -> 0 )

This way every object with expireAfterSeconds: BSONDateTime in this collection will expire after the date specified But I don't even know what these booleans are responsible for.

0
Darren Bishop On

On my project we have this function

  def ensureIndex(
               key: List[(String, IndexType)],
               name: Option[String] = None,
               unique: Boolean = false,
               background: Boolean = false,
               dropDups: Boolean = false,
               sparse: Boolean = false,
               version: Option[Int] = None,
               options: BSONDocument = BSONDocument()) = {

  val index = Index(key, name, unique, background, dropDups, sparse, version, options)
  log.info(s"Ensuring index: $index")
  collection.indexesManager.ensure(index)
}

And I use it like the following for TTL indexes ($doc comes from the BSON DSL):

ensureIndex(List("lastModifiedOn" -> IndexType.Ascending), options = $doc("expireAfterSeconds" -> 30))