I have a case where a mongodb document contains an array of sub documents, and this array may contain an array of sub documents etc.. The structure is presented below.
{"Form_Reference": "1",
"Form_Name": "new Test",
"Form_Title": "new Test",
"Form_Version": "1",
"Form_Department": "1",
"Form_Specialty": "1",
"Form_UserType": "1",
"Form_Components": [{
"Comp_Code": "1",
"Comp_Name": "1",
"Comp_Version": "1",
"Comp_Order": "0",
"Comp_Title": null,
"Comp_Description": null,
"Comp_Column": "1",
"Comp_EditColor": null,
"Comp_Elements": "1",
"Comp_Components": [{
"Comp_Code": "2",
"Comp_Name": "2",
"Comp_Version": "2",
"Comp_Order": "0",
"Comp_Title": null,
"Comp_Description": null,
"Comp_Column": "2",
"Comp_EditColor": null,
"Comp_Elements": "2",
"Comp_Components": []
}]
}]
}
I want to delete the document contained in the deepest sub-array having Comp_Code = "2".
After reading many forums and posts, I have concluded that the MongoDb c# driver Builders methods (Builders.Update.Pullfilter) are not fitted for that kind of operation. (Reference : https://groups.google.com/forum/#!topic/mongodb-csharp)
So far, I was able to find the element through the following syntax: (please note that the 'col' variable used below has the following definition:)
var col = db.GetCollection<BsonDocument>("tbl_Form_Skeleton");
var bsonquery3 = "{'Form_Components':{$elemMatch:{'Comp_Components':{$elemMatch:{'Comp_Code' : '3'}}}}}";
var filter3 = BsonSerializer.Deserialize<BsonDocument>(bsonquery3);
var result = col.FindSync(filter3).ToList().ToJSON;
Upon execution, result variable is filled with a value.
On the other hand, when I try to pull the element from the array,using that same nothing happens :
var bsonQuery1 = "{}";
var filter1 = BsonSerializer.Deserialize<BsonDocument>(bsonQuery1);
var bsonQuery2 = "{$pull:{'Form_Components':{$elemMatch:{'Comp_Components':{$elemMatch:{'Comp_Code' : '3'}}}}}}";
var filter2 = BsonSerializer.Deserialize<BsonDocument>(bsonQuery2);
col.UpdateOne(filter1, filter2);
"{$pull:{'Form_Components':{$elemMatch:{'Comp_Components':{$elemMatch:{'Comp_Code' : '3'}}}}}}". That's a "string" in JSON Format. You can use the native language instead of doing that.