Liran Friedman
Liran Friedman

Reputation: 4287

C# - MongoDB how to remove an item from multiple nested arrays by element value?

I have this JSON structure in a mongo db collection:

{
    "Id":"123",
    "Product": "test",
    "Tags":[
        {
            "Name": "name",
            "Categories": [
                {
                    "Name": "test",
                    "OtherValue": ...
                }
            ]
        },
        {
            "Name": "name",
            "Categories": [
                {
                    "Name": "test",
                    "OtherValue": ...
                }
            ]
        }
    ]
}

Is there a way to be able to remove an item from all of the nested "Categories" arrays by the item's "Name" property?

For example, remove all categories where "Name" == "test"?

I tried something like this:

var filter = Builders<Item>.Filter.Eq(item => item.Id, "123");
var update = Builders<Item>.Update.Pull("Tags.$[].Categories[i]", "test");

var arrayFilters = new List<ArrayFilterDefinition>
{
    new JsonArrayFilterDefinition<Setup>("{\"i.Name\": \"test\"}")
};

var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters };
await Collection.UpdateOneAsync(filter, update, updateOptions);

But it didn't work... Any ideas?

Upvotes: 2

Views: 2644

Answers (1)

s7vr
s7vr

Reputation: 75934

Try positional all $[] variant.

var filter = Builders<Item>.Filter.Eq(item => item.Id, "123");
var update = Builders<Item>.Update.PullFilter("Tags.$[].Categories", Builders<BsonDocument>.Filter.Eq("Name", "test"));

await Collection.UpdateOneAsync(filter, update);

Upvotes: 4

Related Questions