Remove many 2-dimensional array elements in MongoDB in Go

Hello Team,

I have been referring following thread -

and solution suggested by Mr Wan Bachtiar.

Solution given by Mr Wan Bachtiar works for a hardcoded single dimension array value. However, I am not able to execute it successully if I want to delete MANY 2-dimensonal array elements using $pull.

Sample data for Student collection :

{"_id":{"$oid":"5ed0cb4cb8d5570916d1ee7e"},"studentid":"01","studentname":"XYZ","details":[{"subject": "maths", "marks":50} ,{"subject": "science", "marks":60} ,{"subject": "sports", "marks":40}]}

Let’s assume I want to remove data for subejcts & marks for maths & science from above student’s document.

I tried it like but no luck -

collection := client.Database("users").Collection("student")
filter := bson.M{}

Appraoch 1 :

updates := bson.M{"$pull": bson.M{"details": bson.M{"$in": bson.A{bson.M{{"subject": "maths", "marks":50}, {"subject": "science", "marks":60}}}}},}

Appraoch 2 :

I also tried it using array of string -

var detailsArr []string
		for index := 0; index < len(student.details)-1; index++ { // Except last one

			subInfo := "\"" + "subject" + "\"" + ":" + "\"" + student.details[index].subject + "\"" + "\"" + "marks" + "\"" + ":" + "\"" + student.details[index].marks + "\""

			detailsArr = append(detailsArr, subInfo)
		}
		
		updates := bson.M{
			"$pull": bson.M{"details": bson.M{"$in": bson.A{detailsArr}}},
		}

result, err := collection.UpdateMany(context, filter, updates) --- tried with UpdateOne also.

Please help me on this as I stuck here. Generic solution mentioned in approach #2 would be better as I can’t use hard-coded stuff in my code.

PS : I am using mongo-go-driver.

Thanks a lot !

After few more try out, I did added following code -

           detailsArr := bson.A{}
           for index := 0; index < len(student.details)-1; index++ { // Except last one
                   subInfo := bson.M{"subject": student.details[index].Subject, "marks": student.details[index].Marks}
                   detailsArr  = append(detailsArr, subInfo)
           }
           
           updates := bson.M{
                   "$pull": bson.M{"details": bson.M{"$in": detailsArr}},
                   "$set":  bson.M{"processedtime": processedTime},
           }
		   
           result, err := collection.C.UpdateOne(context, filter, updates)

However, here I see another issue. As I have many student documents in my collection data and each student contains 4 array elements (subject/marks) and my aim is to remove all array elements Except last one.
I see weird behavior (on execution of above code), sometimes 3 array elements get deleted for a student, 2 for another student, 3 for third student and so on. I mean there is no conssitency in behaviour of $pull here ?

Please correct me what I am doing wrong here.