C#Mongo删除子文档的子文档

时间:2017-06-27 04:10:34

标签: c# mongodb mongodb-query

我的收藏中有以下文件:

{
    "Target_Year" : 2017,
    "Target_Month" : 6,
    "Performance" : [ 
        {
            "Report_Day" : 1,
            "SM_Name" : "RACHEL",
            "Total" : [{"SM": "A"},
                       {"SM": "B"}
                      ]
        }, 
    ]
}

我的代码

var builder = Builders<BsonDocument>.Filter;
var filterMain = builder.Eq("Target_Year", "2017") & builder.Eq("Target_Month", "6");
var filterPerf = builder.Eq("Report_Day", "1");
mongoDB.SuperiorPerformance.FindOneAndUpdate(filterMain, Builders<BsonDocument>.Update.PullFilter("Performance", filterPerf));

如何将我的代码修改为仅从Total中删除{“SM”:“A”}?

1 个答案:

答案 0 :(得分:1)

您需要匹配查询中的“外部”数组以进行选择,然后使用positional $ operator路径中的$pull来解决正确的数组元素:

var builder = Builders<BsonDocument>.Filter;
var filterMain = builder.Eq("Target_Year", 2017) & builder.Eq("Target_Month", 6)
   & builder.Eq("Performance.Report_Day", 1);

var filterTotal = builder.Eq("SM", "A");

mongoDB.SuperiorPerformance.FindOneAndUpdate(
  filterMain,
  Builders<BsonDocument>.Update.PullFilter("Performance.$.Total", filterTotal));

与此相同:

.update(
  { "Target_Year": 2017, "Target_Month": 6, "Performance.Report_Day": 1 },
  { "$pull": { "Performance.$.Total": { "SM": "A" } } }
)

运行并测试并给出结果:

{
        "_id" : ObjectId("5951e89738470d375d40ac9e"),
        "Target_Year" : 2017,
        "Target_Month" : 6,
        "Performance" : [
                {
                        "Report_Day" : 1,
                        "SM_Name" : "RACHEL",
                        "Total" : [
                                {
                                        "SM" : "B"
                                }
                        ]
                }
        ]
}