Chee Mun
Chee Mun

Reputation: 85

C# Mongo remove sub document of sub document

I has the following documents in my collection:

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

My Code

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

How can I amend my codes to ONLY REMOVE {"SM": "A"} from Total?

Upvotes: 1

Views: 1023

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151112

You need to also match the "outer" array in the query to select, then use the positional $ operator in the path to $pull in order to address the correct array element:

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

Works to the be the same as this:

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

Run and tested and gives me the result:

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

Upvotes: 1

Related Questions