MongoDB .Net driver 2.0 Pull (remove element)
When using a filter to remove array elements, you need to use the PullFilter
builder instead of Pull
(which matches whole elements).
var collection = db.GetCollection<Person>("people");
var filter = new BsonDocument("username", "bodrum");
var update = Builders<Person>.Update.PullFilter("followerList",
Builders<Follower>.Filter.Eq("follower", "fethiye"));
var result = collection.FindOneAndUpdateAsync(filter, update).Result;
Or somewhat more succinctly, using lambdas:
var update = Builders<Person>.Update.PullFilter(p => p.followerList,
f => f.follower == "fethiye");
var result = collection
.FindOneAndUpdateAsync(p => p.username == "bodrum", update).Result;
Assuming you have a collection name Person, You can use PullFilter to remove the records from array
var filterBuilder = Builders<Person>.Filter.Eq(person => person.username, "bodrum");
var updateBuilder = Builders<Person>.Update.PullFilter(p => p.followerList,
Builders<Person>.Filter.Eq(per => per.follower, "fethiye"));
var updateResult = collection.UpdateOne(filterBuilder, updateBuilder);
Console.WriteLine(
$"MatchedCount: {updateResult.MatchedCount}, ModifiedCount: {updateResult.ModifiedCount}");
If we also need to remove array of values inside a filtered document we can replace the update builder with this line
var updateBuilder = Builders<Person>.Update.PullFilter(p => p.followerList,
Builders<Person>.Filter.In(per => per.follower, new List<string> {"fethiye", "izmir"}));
Also to save many document, updateOne can be replace with updateMany
var updateResult = collection.UpdateMany(filterBuilder, updateBuilder);