Updating multiple Array elements in mongoDB not working

public class Details
{
    [BsonId]
    public ObjectId Id { get; set; }
    public string GroupID { get; set; }
    public Names[] Name{ get; set; }
}

public class Names
    {
        public string FullName { get; set; }
        public int Age { get; set; }
        public int Status {get; set;}
     }

Input:

var req = [{FullName = "ABC",
            Age = 15,
            Status = 0}
            {FullName = "XYZ",
            Age = 16,
            Status = 0},
            {FullName = "QAZ",
            Age = 14,
            Status = 0}]

MongoDB Query:

var updateDefinationValues = new List<UpdateDefinition<Details>>();
List<FilterDefinition<Details>> listDetailsFilter = new List<FilterDefinition<Details>>();
foreach (var il in req.Names)
{
    FilterDefinition<Details> detailsFilter = Builders<Details>.Filter.Where(x => x.GroupID == requestId && x.Names.Any(i => i.FullName == il.FullName));
    updateDefinationValues.Add(Builders<Details>.Update.Set(x => x.Names.ElementAt(-1).Status, 1));
    listDetailsFilter.Add(detailsFilter);
}
FilterDefinition<Details> filter = Builders<Details>.Filter.Or(test);
var combinedUpdate = Builders<Details>.Update.Combine(updateDefinationValues);
var isUpdated = UpdateOne(_db, filter, combinedUpdate);

The above query is working when listDetailsFilter count == 1.

Error: The positional Operation did not find the match needed for this query

And it is not working when listDetailsFilter count > 1.

Hi, @Rahul_Naik,

The .NET/C# Driver includes support for the positional $ operator, which will update the first matched element. It does not however include support yet for the all positional $[] operator. Please vote on and follow CSHARP-2232 for additional information including possible workarounds.

Sincerely,
James

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.