简体   繁体   中英

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

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

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, eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM