How can I delete nested array element in a mongodb document with the c# driver

You are calling method Pull(string name, MongoDB.Bson.BsonValue value) and according to the docs it

Removes all values from the named array element that are equal to some value (see $pull)

and you provide { "Identifier", productId } as the value. I guess that mongo does not find that exact value.

Try to use the second overload of Pull with query-condition instead of exact value

Removes all values from the named array element that match some query (see $pull).

var update = Update.Pull("Products", Query.EQ("Identifier", productId));

UPDATE

Since you mention Category entity so I can suggest using lambda instead of Query.EQ:

var pull = Update<Category>.Pull(x => x.Products, builder =>
builder.Where(q => q.Identifier == productId));

Solution with C# MongoDB Driver. Delete a single nested element.

var filter = Builders<YourModel>.Filter.Where(ym => ym.Id == ymId);
var update = Builders<YourModel>.Update.PullFilter(ym => ym.NestedItems, Builders<NestedModel>.Filter.Where(nm => nm.Id == nestedItemId));
_repository.Update(filter, update);

I was also facing the same problem and then finally after doing lot of R&D, I came to know that, you have to use PullFilter instead of Pull when you want to delete using filter.

Tags:

C#

Crud

Mongodb