我有一个像这样的对象:
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;}
}
我想在bar ID列表中更新多个bar basead。我正在尝试做类似的事情,但它只更新一条记录而不是多条记录:
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;
}
我该怎么做?
答案 0 :(得分:3)
这是一个适用于我的版本,使用最新版本的驱动程序(v2.7) - 我认为它适用于v2.5以后:
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;
}