Error when trying to update MongoDb array element

后端 未结 1 736
南笙
南笙 2021-01-14 00:30

In my Azure CosmosDb MongoApi I have JSON with an embed array of documents.

{
    \"_id\": ObjectId(\"5a95745df886842904b82f71\"),
    \"token\": \"value1\",         


        
相关标签:
1条回答
  • 2021-01-14 01:15

    Positional operator is not currently supported by Cosmos DB. Please use the following workaround: iterate over documents and array elements on the client side, change the required element and issue an update on the document with new array:   For example, assuming you have a collection users of following elements:

    { 
        "_id" : ObjectId("59d6b719708b990d6c9b3aca"), 
        "tags" : [
            {
                "id" : 1, 
                "value" : "11"
            }, 
            {
                "id" : 2, 
                "value" : "22"
            }, 
            {
                "id" : 3, 
                "value" : "32"
            }
        ]
    }
    
     
    

    …you can issue the following command to get one of the elements (with id=1 in this case) updated:  

    db.users.find().forEach( 
            function(user) 
            { 
             user.tags.forEach( 
             function(tag) 
             {
                   if (tag.id=="1")
                   {
                           tag.value = "Updated!";                          
                           db.users.updateOne({_id : user._id}, {$set: {"tags": user.tags}});
                   }
            }
            );
           }  
    );
    

    You can adjust the condition in if() with even finer granularity than positional operator allows.

    0 讨论(0)
提交回复
热议问题