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

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

 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:


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.


No comments:

Post a Comment