Search code examples
scalamongodbcasbah

Upsert with increment of embedded object value in MongoDB / Casbah / Scala /


I need to increment the count of an embedded object's value for a property, or create the object property if it doesn't exist, or create the entire record if there isn't one, using Casbah for MongoDB in Scala. Also interested in hearing how to do this in Mongo directly, if it's possible at all.

For example, if there are no objects in the collection, start by adding a record with the given _id, and an object in the vals default value 1 for property a. This query doesn't work, but looks something like I expect it would:

import com.mongodb.casbah.Imports._
coll.update(MongoDBObject("_id" -> "obj1"), $inc("vals" -> Map("a" -> 1)), true, false)

This shold result in the following record:

{ "_id" : "obj1", "vals" : { "a" : 1} }

Now upsert a new object into the vals:

coll.update(MongoDBObject("_id" -> "obj1"), $inc("vals" -> Map("b" -> 1)), true, false)

Yielding:

{ "_id" : "obj1", "vals" : { "a" : 1, "b" : 1 } }

Finally, upsert / increment the value for the b property of the vals, using exactly the same query as in the previous step:

coll.update(MongoDBObject("_id" -> "obj1"), $inc("vals" -> Map("b" -> 1)), true, false)

Yielding:

{ "_id" : "obj1", "vals" : { "a" : 1, "b" : 2 } }

Solution

  • Turned out to be very easy:

    coll.update(MongoDBObject("_id" -> "obj1"), $inc("vals.a" -> 1), true, false)