Search code examples
indexingsalatmongodb-scala

Ensuring indexes with MongoDB using Salat DAOs


There is a post on composite keys using Salat, but information on ensuring indexes (from mongo-db console, db.collection.ensureIndex({someField : 1})) is lacking. Looking through Salat source, I didn't see an annotation for marking a field as needing an index, is there a way to do this?


Solution

  • It is possible by directly accessing the MongoCollection from within the DAO object yourself (see: this forum post). E.g.:

    object AlphaDAO extends SalatDAO[Alpha, Int](collection = MongoConnection()("test_db")("test_coll")) {   
      val beta = new ChildCollection[Beta, Int](
        collection = MongoConnection()("test_db")("test_col1_subcol1"),
        parentIdField = "alphaId") {}
    
      import com.mongodb.casbah.Imports._
      collection.ensureIndex(DBObject("some.field" -> 1, "anotherField" -> 1))
    
      beta.collection.ensureIndex(DBObject("some.field" -> 1, "anotherField" -> 1))
    }