0

I'm trying to update just a few nested documents on my .Net Application, but I don't know exactly how to do that.

Here is one of the topics I've been searching after making this question:

C# - MongoDB - Update an element inside a Nested Document

**DataBase Object: **

{
    "_id" : ObjectId("5d03a6f5fba276260c4911bd"),
    "costumerId" : ObjectId("5c050cdefba2771eac58c84b"),
    "order" : 106376,
    "items" : [ 
        {
            "itemId" : 10226905,
            "date" : ISODate("2018-11-30T14:00:00.000Z"),
            "description" : "itemA",
            "new" : true,
        }, 
        {
            "itemId" : 10226906,
            "date" : ISODate("2018-11-30T14:00:00.000Z"),
            "description" : "itemB",
            "new" : true,
        }, 
        {
            "itemId" : 10226907,
            "date" : ISODate("2018-11-23T14:00:00.000Z"),
            "description" : "ItemC",
            "new" : true,
        }, 
        {
            "itemId" : 10226908,
            "date" : ISODate("2018-11-23T14:00:00.000Z"),
            "description" : "ItemD",
            "new" : false,
        }, 
    ]
}

MongoDB Update Query:

db.CostumerProducts.update(
    {costumerId: 106376},
    {
        $set:{'items.$[element].new': true}
    }, 
    {
        multi:true, 
        arrayFilters: [ 
        {
            'element.itemId':{
                $in:[10226905,10226906,10226907]
             }
        }]
    })

C# Update Query using MongoDB driver:

var arrayObjects = List<int>{10226905,10226906,10226907};
var filter = Builders<CostumerProductsObject>.Filter.And(new[]  
{
    new FilterDefinitionBuilder<CostumerProductsObject>().Eq(p=>p.costumerId, costumerId), 
    new FilterDefinitionBuilder<CostumerProductsObject>().Eq(p=>p.order, order),
});

var set = Builders<ItemsObject>.Update.Set("items.$[element].new", true);

var arrayFilter = new FilterDefinitionBuilder<ItemsObject>().In(a=>a.itemId, itemsArray);

 using (var db = new MongoContextInfra())
{
    db.Set<CostumerProductsObject>(CollectionName).UpdateMany(filter, 
         set,
         new UpdateOptions
         {
             ArrayFilters = null
         });
}

I expect to update just the three items into "arrayObjects" variable.

Can you show me some code or help me fixing mine so I can make this update? thanks.

Glenn Mateus
  • 319
  • 1
  • 2
  • 17

0 Answers0