skip to Main Content

I want only items in list entityParameters will update in x.Params
by Id , update all items of entityParameters if entityParameters.Id == x.Params.Id

List<Param> entityParameters

filter = Builders<MachineObj>.Filter.Where(x => x.MachineId == id);

update = Builders<MachineObj>.Update
            .Set(x => x.Params, entityParameters);

2

Answers


  1. Chosen as BEST ANSWER
            List<ArrayFilterDefinition> arrayFilters = new();
            int i = 0;
            foreach (var item in entityParameters)
            {
                var updateItem = Builders<MachineObj>.Update.Set($"Params.$[elem{i}]", item);
    
                arrayFilters.Add(new BsonDocumentArrayFilterDefinition<BsonDocument>(
                   new BsonDocument($"elem{i}.ParamId", item.ParamId)
                ));
    
                update = Builders<MachineObj>.Update.Combine(update, updateItem);
    
                i++;
            }
    
            updateOptions = new UpdateOptions
            {
                ArrayFilters = arrayFilters
            };
    
        await machinesDB.Machines.UpdateOneAsync(filter, update, updateOptions);
    

  2. Here is an approach to update only the items in x.Params that match the Id of items in entityParameters, using the MongoDB C# driver. This involves iterating over entityParameters and creating update definitions for each item:

    List<Param> entityParameters = ...;
    
    var filter = Builders<MachineObj>.Filter.Eq(x => x.MachineId, id);
    
    var updateBuilder = Builders<MachineObj>.Update;
    
    UpdateDefinition<MachineObj> combinedUpdate = updateBuilder.Combine();
    
    foreach (var param in entityParameters)
    {
        var arrayFilter = Builders<MachineObj>.Filter.ElemMatch(x => x.Params, p => p.Id == param.Id);
    
        var update = updateBuilder.Set(x => x.Params[-1], param);
    
        combinedUpdate = updateBuilder.Combine(combinedUpdate, update);
    }
    
    var result = collection.UpdateOne(filter, combinedUpdate);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search