0

Given following domain model:

case class Benefits(id: Int, benefitPlan: String, comment : String)

case class Employee(empNum : Int, benefits : List[Benefit])

I've been using Salat to help derialize/deserialize these objects. However, I'm a little confused as to how to delete/update a specific object from the benefits List in employee object given that I know the benefit.id of the object that is to be deleted/updated?

I do not want to iterate the full benefits list to be able to update a single object since this list may hold large number of objects at runtime. Is there a better way than getting the emp object, iterating the list until desired object is found, update it and then save the emp object back?

cracked_all
  • 1,331
  • 1
  • 11
  • 26

2 Answers2

2

In this case, I would say your benefits should be an Map[Int, Benefits].

If you use Map, your update/delete will be O(1) instead of linear time.

List is not a good choice if you need randomly access and update an element in it.

Brian Hsu
  • 8,781
  • 3
  • 47
  • 59
0

I'd suggest looking into this article about Casbah and Salat (assuming you're using salat for MongoDB)

def removeBenefit(empNum : Int, benefitId: Int)= {
  val updateQuery = $pull("benefits " -> MongoDBObject("id" -> benefitId))
  val query = MongoDBObject("empNum " -> empNum )
  modify(query, updateQuery) // your findAndModify operation goes here
}