Mongo DB从嵌套数组中拉出

时间:2017-07-27 09:50:29

标签: c# mongodb

我有一个案例,mongodb文档包含一个子文档数组,这个数组可能包含一个子文档数组等。结构如下所示。

{"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": []
    }]
}]
}

我想删除包含Comp_Code =“2”的最深子数组中包含的文档。 在阅读了很多论坛和帖子之后,我得出结论,MongoDb c#driver Builders方法(Builders.Update.Pullfilter)不适合这种操作。 (参考:https://groups.google.com/forum/#!topic/mongodb-csharp

到目前为止,我能够通过以下语法找到该元素: (请注意,下面使用的'col'变量具有以下定义:)

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;

执行时,结果变量将填充一个值。

另一方面,当我尝试从数组中提取元素时,使用相同的方法没有任何反应:

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

0 个答案:

没有答案