[CSHARP-2555] How to delete the nested document using C# Created: 19/Mar/19  Updated: 27/Oct/23  Resolved: 01/Apr/19

Status: Closed
Project: C# Driver
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Task Priority: Major - P3
Reporter: Lawrence Assignee: Wan Bachtiar
Resolution: Works as Designed Votes: 0
Labels: question
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Attachments: PNG File image-2019-03-19-15-01-32-862.png    

 Description   

Hi Everyone,

 

 

This is my DB structure in Mongo, Now I want to delete the nested document based on the attributeValueId as shown above, I used this code in C# but it's not working

var filter = Builders<DimensionsDL>.Filter.Eq(item => item.Id, id);
var update = Builders<DimensionsDL>.Update.Pull("columns.$[].values", Builders<AttributeValueDL>.Filter.Eq(x => x.AttributeValueId, attributeValueId));

UpdateResult updateResult = _mongoCollection.UpdateOne(filter, update);

 

I am passing the _id and attributeValueId from UI,

I am getting the Matched count 1 in the result but ModifiedCount is 0, Please help me on this.



 Comments   
Comment by Wan Bachtiar [ 27/Mar/19 ]

Hi Lawrence,

You need to use PullFilter() instead of Pull() when specifying a filter for a nested array.

For example:

var itemID = new ObjectId("...");
var attributeValueID = new ObjectId("...");
 
var filter = Builders<Item>.Filter.Eq(item => item.Id, itemID);
var update = Builders<Item>.Update.PullFilter("Columns.$[].Values", 
                            Builders<Value>.Filter.Eq(x => x.AttributeValueId, attributeValueID));
 
UpdateResult updateResult = collection.UpdateOne(filter, update); 

Please note that the CSHARP project is for reporting bugs or feature suggestions for the MongoDB .NET/C# driver. If you have any follow-up questions on the use of the C# driver, please post a question on mongodb-user group with the relevant information.

Regards,
Wan.

Generated at Wed Feb 07 21:42:52 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.