Updating an embedded document in MongoDB with official C# driver

前端 未结 1 2028
梦毁少年i
梦毁少年i 2020-12-29 16:13

If I have a Company collection which contains embedded Divisions:

{ 
  \"_id\": 1 
  \"_t\": \"Company\", 
  \"Name\": \"Test Company\" 
  \"Divisions\": [ 
         


        
相关标签:
1条回答
  • 2020-12-29 16:42

    You could use the positional array modification feature of MongoDB to update an entire division in the array at once as follows:

    var division = GetDivisionById(1);
    division.Name = "New Name";
    // change any other properties of division you want
    collection.Update(
        Query.EQ("Divisions._id", 1),
        Update.Set("Divisions.$", BsonDocumentWrapper.Create<IDivision>(division))
    );
    

    The key things going on here are:

    1. The use of the "$" in Update.Set
    2. Since Update.Set requires a BsonValue as its second argument we have to use a BsonDocumentWrapper to hold the division value (the IDivision type parameter to Create sets the nominalType at serialization to IDivision which results in the "_t" discriminator being written).
    0 讨论(0)
提交回复
热议问题