Cokorda Raka
Cokorda Raka

Reputation: 4535

Specifying MongoDBObject as content of $set

I need to construct an update query like this:

{
  $set: {"yow": 1, "man": 2},
  $setOnInsert: {"a": 3},
}

I just don't know how to do it using Cashbah. The thing is the value for the $set, I got it from a JSON String (which I parsed into MongoDBObject). So I have a code like this:

val setVal = JSON.parse(jsonString).asInstanceOf[MongoDBObject]
val updateQuery = $set(...) ++ $setOnInsert("a" -> 3)

I don't know what to put in the "...". I tried:

val updateQuery = $set(setVal) ++ $setOnInsert("a" -> 3)

But I got a compilation error that says:

type mismatch;  found: com.mongodb.casbah.commons.MongoDBObject  required: (String, ?)

I also tried:

val updateQuery = $set(setVal.toSeq) ++ $setOnInsert("a" -> 3)

Got similar error:

type mismatch;  found: Seq[(String, AnyRef)]  required: (String, ?) 

tried with toMap, same thing.

Thanks in advance for your help!, Raka

Upvotes: 0

Views: 202

Answers (1)

Ross
Ross

Reputation: 18111

Very close $set takes varargs of fields (String, A)* so this will work:

$set(setVal.toSeq: _*) ++ $setOnInsert("a" -> 3)

Alternatively, you could opt out the dsl for the $set part:

MongoDBObject("$set" -> setVal) ++ $setOnInsert("a" -> 3)

Upvotes: 2

Related Questions