Modifying the last element of an array in MongoDB

前端 未结 2 1287
南旧
南旧 2020-12-17 19:41

I have an object structure like this:

 {
    name: \"...\",
    pockets: [
        {
            cdate: \"....\",
            items: [...]
        }
                 


        
2条回答
  •  感动是毒
    2020-12-17 20:29

    I don't believe it is possible to do it atomically. There is a request for this functionality to be added to MongoDB.

    If you can assure thread-safety in your application code, you could probably use a sequence of $pop from pockets array (that removes the last element from pockets) to variable p and then $addToSet to p.items, now you can $push p back into pockets. But if your application doesn't have a way to assure only one process may be doing this at one time, then another process could modify the array in the middle of those steps and you may end up losing that update.

    You might also look into "Update if current" semantics here to see another way you can work around possible race by multiple threads issue.

提交回复
热议问题