Search code examples
c#arraysmongodbmongodb-.net-drivermongodb-update

MongoDB .NET Driver - Using pullFilter to remove string from string array


I am trying to do a pullFilter and can get it to work on complex types.

await _Collection.UpdateOneAsync(
Builders<Descriptor>.Filter.Eq(d => d.Id, id),
Builders<Descriptor>.Update
    .Set(d => d.UpdatedBy, actioner)
    .Set(d => d.UpdatedOn, DateTime.Now)
    .PullFilter(d => d.Options, "Remove this one")
);

However, Options is an array of string values and I cannot get it to remove the value "Remove this one":

{
    "Name" : "Test",
    "Type" : NumberInt(1),
    "Options" : [
        "Testing",
        "Tested",
        "Remove this one"
    ]
}

This is my error message:

"message": "JSON reader was expecting a value but found 'Remove'."

I also tried this:

await _Collection.UpdateOneAsync(
    Builders<Descriptor>.Filter.Eq(d => d.Id, id),
    Builders<Descriptor>.Update
        .Set(d => d.UpdatedBy, actioner)
        .Set(d => d.UpdatedOn, DateTime.Now)
        .PullFilter(d => d.Options, d => d == "Remove this one")
);

which results in this error:

"message": "{document} is not supported."


Solution

  • You should use UpdateDefinitionExtensions.Pull<TDocument, TItem> Method (UpdateDefinition, FieldDefinition, TItem) instead of .PullFilter().

    await _Collection.UpdateOneAsync(
        Builders<Descriptor>.Filter.Eq(d => d.Id, id),
        Builders<Descriptor>.Update
            .Set(d => d.UpdatedBy, actioner)
            .Set(d => d.UpdatedOn, DateTime.Now)
            .Pull(d => d.Options, "Remove this one")
    );
    

    Demo

    enter image description here