Search code examples
mongodbmongodb-.net-driver

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?


Solution

  • 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);