2

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?

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Works with a minor adjustment: var update = Builders<Item>.Update.PullFilter("Tags.$[].Categories", Builders<BsonDocument>.Filter.Eq("Name", "test")); Just remove the [] from Categories[] to Categories

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.