1

I have an object like that:

public class Foo {
     public string Id {get;set;}
     public List<Bar> Bars {get;set;}
}

public class Bar {
     public string Id {get;set;}
     public bool Read {get;set;}
}

I would like to update multiple bars basead on a list of bar ids. I am trying to do something like that, but it only updates one record instead of multiple:

public bool MarkAsRead(string fooId, List<string> barIds)
        {
            var @in = new FilterDefinitionBuilder<Bar>().In(x => x.Id, barIds);

            var filter = Filter().Eq(x => x.Id, fooId) & Filter().ElemMatch(x => x.Bars, @in);

            var update = UpdateFilter()
                .Set(x => x.Bars[-1].Read, true);

            var result = collection.UpdateOne(filter, update);

            return result.MatchedCount > 0;
        }

How can I do that?

1

1 Answer 1

4

Here's a version that works for me using the latest version of the driver (v2.7) - I think it works from v2.5 onwards:

public bool MarkAsRead(string fooId, List<string> barIds)
{
    Expression<Func<Foo, bool>> filter = f => f.Id == fooId;
    var update = Builders<Foo>.Update.Set("Bars.$[i].Read", true );
    var arrayFilters = new List<ArrayFilterDefinition> { new JsonArrayFilterDefinition<Bar>("{'i._id': { $in: ["+string.Join(",", barIds.Select(s => string.Format("\"{0}\"", s)).ToArray())+"]}}") };
    var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters };

    var result = collection.UpdateOne(filter, update, updateOptions);

    return result.MatchedCount > 0;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, do you know if it is possible using just Expression instead of strings? I was string trying but no sucess.
That's currently impossible. Only BSON and JSON can be used for array filters.
You might perhaps be able to implement your own version of an ArrayFilterDefinition, - not sure, got no VS just now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.