Note Use the mongodb shell to execute the codes.
Say I have one student document below
{ "_id" : 4, "grades" : [ { "grade" : 80, "mean" : 75, "std" : 8 }, { "grade" : 85, "mean" : 90, "std" : 5 }, { "grade" : 85, "mean" : 90, "std" : 5 }, { "grade" : 85, "mean" : 95, "std" : 6 }, { "grade" : 90, "mean" : 85, "std" : 5 } ] }
We have two problems:
Problem 1 : let's say you want to update all subdocuments with _id = 4 && & grades.grade = 85 && grades.std = 5, with std = 6 you will write as follows
db.students.update( {'$and':[ { _id: 4},{ "grades.grade": 85 }, {"grades.std": 5 } ]}, { $set: { "grades.$.std" : 6 } } );
Now, if you execute the statement above several times (3 times), then ideally it should update the 2nd, 3rd subdocuments
But the last subdocument is also updated by beacause, it has std = 5 match, but we set the condition as $, not $ or, and then how is the last document updated?
Problem 2: Now suppose you want to delete the subdocument itself that matches the query criteria. I tried the following instruction
db.students.update({_id:4,'grades.grade':85},{'$unset':{'grades.$':1}})
because $ unset will put null in case of subdocuments / arrays, how to solve this problem?
How to replicate in mongodb console?
db.students.insert( { "_id" : 4, "grades" : [ { grade: 80, mean: 75, std: 8 }, { grade: 85, mean: 90, std: 5 }, { grade: 85, mean: 90, std: 5 }, { grade: 85, mean: 95, std: 6 }, { grade: 90, mean: 85, std: 5 } ] });