Is it possible to get the current document field value while updating it similar to the $where operator?
I'm trying to insert(or update) a field with a key name that is the value of another key in the updated document.
I'm using casbah with Scala :
DB.update(
MongoDBObject("$where" -> jSFunctionAsString()),
$addToSet(**this._id** -> "someVal"), multi = true)
)
def jSFunctionAsString() = """
function f(){
return this._id > 3
}
"""
So what I'm trying to do is using the _id field as a key for the inserted/updated field which works when using $where but I want to use it in $addToSet as well.
I've read that I can maybe use $findandmodify but the query takes too long comparing to $update
Edit- example :
Collection:
{ "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2 }
{ "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1 }
{ "_id" : 3, "item" : "xyz", "price" : 5, "quantity" : 5 }
{ "_id" : 4, "item" : "abc", "price" : 10, "quantity" : 10 }
{ "_id" : 5, "item" : "xyz", "price" : 5, "quantity" : 10 }
for object in collection :
DB.update(
MongoDBObject("$where" -> jSFunctionAsString()),
$addToSet(**this._id** -> object._id), multi = true)
)
Expected result:
{ "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2 }
{ "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1 }
{ "_id" : 3, "item" : "xyz", "price" : 5, "quantity" : 5 }
{ "_id" : 4, "item" : "abc", "price" : 10, "quantity" : 10, 4:[1,2,3,4,5]}
{ "_id" : 5, "item" : "xyz", "price" : 5, "quantity" : 10, 5:[1,2,3,4,5]}
But I can't really get the updated document id without finding it first(so I have to bring the document to the machine instead of updating it directly in the db)