2

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

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

5 Comments

This solution is inconvenient, I want to find and update the Library object directly in one operation, unless MongoDB doesn't support this functionality.
The array in the referred question is a direct element in the document, which is not the same in my case as the array is an element of a nested document, thanks for the reply.
Thanks for the answer
How to update a property of an element of the array?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.