been trying for some time now to run a delete query against a mongodb collection; strongly typed objects, parents, nested children, each with nested grandchildren. i want to delete a specific grandchild, which is in a specific child, in a specific parent. i can get to MatchedCount = 1, but ModifiedCount is always 0 and the delete doesn't happen. i have tried many variations of the query, both from here and also using the AI engine on the mongo website. nothing works.
The entity structure is what you'd expect:
public class Parent
{
public string Id {get; set;}
public Child[] Children {get; set;}
}
public class Child
{
public Guid Id {get; set;}
public Grandchild[] Grandchildren {get; set;}
}
public class Grandchild
{
public Guid Id {get; set;}
public string Name {get; set;}
}
here is my latest attempt:
var filter = Builders<Parent>.Filter.Eq(x => x.Id, parentId);
var update = Builders<Parent>.Update.Pull(
"Children.$[child].GrandChildren",
Builders<GrandChild>.Filter.Eq(gc => gc.Id, Guid.Parse(grandChildId))
);
var arrayFilters = new List<ArrayFilterDefinition>
{
new BsonDocumentArrayFilterDefinition<BsonDocument>(new BsonDocument("child._id", childId))
};
var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters };
var result = await _parentCollection.UpdateOneAsync(filter, update, updateOptions);
return result.ModifiedCount == 1;
updating/deleting children is simple enough but i cannot get to the grandchild somehow. has anyone any idea what i am doing wrong?
EDIT:
in case anyone else is wrestling with similar - i now have a working solution to this, after 3 days (!!!) and some rehashing some of what i got from mongodb AI. i have used t-sql for 25 years and never suspected that something so simple could be so difficult to figure out. easy when you know how!
var filter = Builders<Parent>.Filter.And(
Builders<Parent>.Filter.Eq(p => p.Id, parentId),
Builders<Parent>.Filter.ElemMatch(p => p.Children, c => c.Id == Guid.Parse(childId)));
var update = Builders<Parent>.Update.PullFilter(
"Children.$.GrandChildren",
Builders<GrandChild>.Filter.Eq(gc => gc.Id, Guid.Parse(grandChildId))
);
var result = await _parentCollection.UpdateOneAsync(filter, update);
return result.ModifiedCount == 1;