2

I want to remove a string from array of strings of a mongodb model, if the string contains substring value

The model is like this

{
    "username": "my_user",
    "str_array": [
        "remove_substring_found/rest_of_string",
        "this_string_wont_be_removed"
    ]
}

Here is what I tried so far, but it is not working

string compare_str = "remove_substring_found";
var filter = Builders<MyModel>.Filter.Eq(s => s.username, "my_user");
var regex = new BsonRegularExpression(string.Format(".*{0}.*", compare_str ), "i");
var filter_update = Builders<string>.Filter.Regex(x => x, regex);
var update = Builders<MyModel>.Update.PullFilter(x => x.str_array, filter_update);
var result = await MyCollection.UpdateOneAsync(filter, update);

1 Answer 1

2

afaik the PullFilter only supports complex objects. it doesn't seem to be working for primitive types such as strings. you're supposed to use the Pull update operator instead for primitives. but the issue with Pull in c# is that it doesn't seem to support regex in a strongly-typed manner. so you need to construct an update definition manually like the following:

var userFilter = Builders<MyModel>.Filter.Where(i => i.username == "my_user");

UpdateDefinition<MyModel> update = "{ '$pull': { 'str_array': /substring_found/ } }";

await collection.UpdateManyAsync(userFilter, update);
Sign up to request clarification or add additional context in comments.

Comments

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.