I have a such a model of MyEntity(s).
[{
id: "1",
ar:
[{
aId: "a",
option: "option-4"
}, {
aId: "b",
option: "option-2"
}, {
aId: "c",
option: "option-3"
}]
}, {
id: "2",
ar:
[{
aId: "d",
option: "option-5"
}, {
aId: "e",
option: "option-6"
}, {
aId: "f",
option: "option-7"
}]
}]
As a result of delete operation I want to remove entries from 'ar' array which satisfies aId and options and in the return I want to have IdWithOptions:
[{
id: "1",
options: [2, 3]
}, {
id: "2",
options: [5, 6]
}]
The only thing, which I don't like, is that I'm using o => options.Contains(o.option) two times, and I don't knnow how to avoid that.
public async Task<IEnumerable<IdWithOptions>> DeletePaths(string aId, IEnumerable<string> options)
{
var builder = new FilterDefinitionBuilder<MyEntity>();
var filter = builder.ElemMatch(m => m.ar, o => o.aId.Equals(aId));
IEnumerable<IdWithOptions> idWithOptions = this.collection
.Find(filter).ToEnumerable()
.Select(o => new IdWithOptions()
{
id = o.id,
options = o.ar.Where(o => options.Contains(o.option)).Select(p => p.option)
})
.ToList();
var pull = new UpdateDefinitionBuilder<MyEntity>()
.PullFilter(m => m.ar, o => options.Contains(o.option));
await this.collection.UpdateManyAsync(filter, pull);
return idWithOptions;
}