Search code examples
scalamongodbcasbah

Efficiently Update a List of Cursor and insert into collection in Casbah


I am querying a collection and I want to update the results.

I want to update a field and let the remaining fields untouched.

I have entries with "filename" and "projectId" as keys

In this case I am doing:

val olderFiles = conn.find(query ++ ("filename" -> filename) ++ ("projectId" -> file.projectId))
val updatedFiles = olderFiles.map{cursor =>
            cursor.put("newField",field)
            cursor
          }

updatedFiles.foreach(conn += _)

However this is slow. How do I update a list of objects in a more efficient manner?

Thank you!


Solution

  • This is what I was looking for:

    conn.update(query ++ ("filename" -> filename) ++ ("projectId" -> projectId),$set ("field" -> field),false,true)
    

    This updates every entry that is found by that query.

    PS: For future reference, if there is a list of fields (.e.g. in this case filenames), instead of using a foreach in these fields and create N queries, one can do this:

    "filename" $in Array(fieldList:_*)