2012-08-25

Unique compound index with Morphia (MongoDb) and Scala

Hi, here's how to create a unique compound index with Morphia and Scala. The example is from my Gradle + Scala + MongoDb application Also, here's Part 1 of my tutorial on building a Scala + Gradle + Guice applications.

package me.m1key.audioliciousmigration.entities.mongodb
import com.google.code.morphia.annotations.Id
import com.google.code.morphia.annotations.Entity
import org.bson.types.ObjectId
import com.google.code.morphia.annotations.Indexes
import com.google.code.morphia.annotations.Index

@Entity
@Indexes(Array(new Index(value = "name, albumName", unique = true)))
class MongoDbSong(val name: String, val albumName: String) {

 @Id
 var id: ObjectId = _
 
 override def equals(that: Any) = {
   that match {
     case that: MongoDbSong => that.name == this.name &&
             that.albumName == this.albumName
     case _ => false
   }
 }

 override def hashCode(): Int = name.hashCode()

}

Remember to run this code in your app:

datastore.ensureIndexes()

Also, my final note here is this: If you make any such changes to your MongoDb schema, you have to drop the collection from the Mongo client.

db.MongoDbSong.drop()

No comments:

Post a Comment