Search code examples
c#.netmongodbmongodb-querymongodb-.net-driver

How to delete an element inside array of a nested document in C# Mongodb strongly typed driver


I am using the official C# MongoDb strongly typed driver version 2.5.0 to interact with MongoDB.

Consider the following classes:

public class Author
{

    public Author()
    {

    }

    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string BirthDate { get; set; }

    public string ScientificDegree { get; set; }

    public Library Library { get; set; }
}

public class Library
{
    public DateTime DateAdded { get; set; }

    public DateTime LastModified { get; set; }

    public List<Book> Books { get; set; }

    [BsonDefaultValue(0)]
    public int ReadCount { get; set; }

}

How to delete a book using it's id from the author library? Here is my code to delete an element from the array directly.

var field = new ExpressionFieldDefinition<Library, List<Book>>(library => library.Books);

var bookFilter = Builders<Book>.Filter.Eq(book => book.Id, bookId);

var update = Builders<Library>.Update.PullFilter(field, bookFilter);

//How to apply the update to the author using author id

Solution

  • You need to get stored Libraryand perform changes to that Library object and update it back to document. Another way you can make use of PullFilter to delete it

    var update = Builders<Author>.Update.PullFilter(x=>x.Library.Books,Builders<Book>.Filter.Eq(x=>x.id,bookId));
    db.Author.UpdateOneAsync(x => x.Id.Equals(autherId), update).Result;
    

    db.Author is collection instance