Reputation: 2172
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
Upvotes: 2
Views: 2259
Reputation: 673
You need to get stored Library
and 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
Upvotes: 4