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 !