2

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)

user_s
  • 1,058
  • 2
  • 12
  • 35
  • I'm trying to understand your question but just not able to -- maybe an example of the results (the before and after documents) your are trying to get would help. – Soren May 30 '16 at 22:26
  • Added example, Thanks – user_s May 31 '16 at 10:28
  • Mongo was never intended to be used like that, so MongoDB may not be the right choice for you -- if this is just a rare query you want to run but still want to use mongo the best I could suggest is to look at Mongo's aggregation framework – Soren May 31 '16 at 13:08

0 Answers0