Search code examples
c#mongodbcollectionsupdatesmongodb-.net-driver

Why MongoDB update affects a single document only?


I have a collection with the following "schema":

{
   "_id": { "$oid": "543cd94799c3ff7a2850a1b6" },
   "Type": 1,
   "Information": [
     {
       "Type" : 2,
       "Colors": [],
       "Heights": [],
       "Widths": []
     }
   ]
}

I have the "Colors", "Heights", "Widhts" arrays nested in array "Information".

I am trying to update some documents in the collection with the following update query:

var query = Query.And(Query.Exists(Entity.INFORMATION + "." + Information.COLORS),
                  Query.Exists(Entity.INFORMATION + "." + Information.HEIGHTS),
                  Query.Exists(Entity.INFORMATION + "." + Information.WIDTHS), 
                  Query.EQ(Entity.TYPE, typeId),
                  Query.ElemMatch(Entity.INFORMATION, Query.EQ(Information.TYPE, informationTypeId)));

var update = MongoDB.Driver.Builders.Update.Set(Entity.INFORMATION + ".$." + Information.WIDTHS, new BsonArray(new Width[0]))
                                       .Set(Entity.INFORMATION + ".$." + Information.COLORS, new BsonArray(new Color[0]))
                                       .Set(Entity.INFORMATION + ".$." + Information.HEIGHTS, new BsonArray(new Height[0]))
                                       .Set(Entity.INFORMATION + ".$." + Information.TYPE, BsonNull.Value);

Collection.Update(query, update, UpdateFlags.Multi);

It seems that only the first document is affected. The rest are not affected.

How to fix this update query to work also for the rest documents? I have used the UpdateFlags.Multi but with no luck..

I want to set Type of Information to null and clear nested arrays inside Information array.


Solution

  • OK, I have flatten the information and now I have only one level of array.

    So, now is working.

    Thank you people.