Delete a item by ID in list inside other list in mongodb using C# .net

Viewed 43

I have a structure like University have a list of classes. Classes have a list of students. I made CRUDs for 3 entities in mongodb and everything is ok, except the delete in the student object.

I have a json like that

{
  "id": "u01",
  "classes": [
    {
      "id": "c01",
      "students": [
        {
          "id": "s01",
          "name": "Ana"
        },
        {
          "id": "s02",
          "name": "Jonh"
        }
      ]
    }
  ]
}

I need pull id S02 using dot.net and tried use pullFilter

    var filter = Builders<University>.Filter.And(Builders<University>.Filter.ElemMatch(doc => doc.Classes, c => c.Id == "c01"));
    var update = Builders<University>.Update.PullFilter(c => c.Classes.First().Students, item => item.Id == "s02");
    collection.FindOneAndUpdateAsync(filter, update);

I have no exceptions but didn't work. What´s wrong? Ty for help

1 Answers

In order to remove the student from the first class that matched the filter, you'd specify the field in MongoDB like this:

classes.$.students

In C#, you can mimic this by using an index of -1, e.g.:

var update = Builders<University>
  .Update
  .PullFilter(c => c.Classes.ElementAt(-1).Students, item => item.Id == "s02");
Related