Supposing I had the following document in a database:
{"_id":"test", "with space":{"a name":1}}
How can I write a $set query in Casbah to update "with space"."a name" to 2?
I was thinking something along the lines of:
collection.update(MongoDBObject("_id" -> "test"), "'with space'.'a name'" $set 2)
But what if my field names were unknown and I had to compose them at runtime? Is there any way to "escape" them in a safe way? (For example, what if any of them contains single quotes, etc.)
There isn't any explicit escaping required for MongoDB; you can just pass a variable name, eg:
val key = MongoDBObject(name + '.' + embeddedname -> "somevalue")
or
val key = MongoDBObject("with space.a name" -> "somevalue")
While MongoDB does allow you to use any valid UTF-8 character in key names aside from '.' and a leading '$', you would generally be best sticking to alphanumeric key names plus underscore.
If you are concerned about safety of user-provided input, see How does MongoDB address SQL or Query injection?