MongoDB - Update objects in a document's array (nested updating)

后端 未结 3 1571

Assume we have the following collection, which I have few questions about:

{
    \"_id\" : ObjectId(\"4faaba123412d654fe83hg876\"),
    \"user_id\" : 123456         


        
3条回答
  •  深忆病人
    2020-11-22 02:13

    There is no way to do this in single query. You have to search the document in first query:

    If document exists:

    db.bar.update( {user_id : 123456 , "items.item_name" : "my_item_two" } , 
                    {$inc : {"items.$.price" : 1} } , 
                    false , 
                    true);
    

    Else

    db.bar.update( {user_id : 123456 } , 
                    {$addToSet : {"items" : {'item_name' : "my_item_two" , 'price' : 1 }} } ,
                    false , 
                    true);
    

    No need to add condition {$ne : "my_item_two" }.

    Also in multithreaded enviourment you have to be careful that only one thread can execute the second (insert case, if document did not found) at a time, otherwise duplicate embed documents will be inserted.

提交回复
热议问题