I have a list of student documents which has the structure like this:
{
"_id" : 0,
"name" : "aimee Zank",
"scores" : [
{
"type" : "exam",
"score" : 1.463179736705023
},
{
"type" : "quiz",
"score" : 11.78273309957772
},
{
"type" : "homework",
"score" : 6.676176060654615
},
{
"type" : "homework",
"score" : 35.8740349954354
}
]
}
As you can see, each student has a list of 4 scores. I need to remove the lowest "homework" score for each student document. Each student has 2 entries for "homewok" type scores (the last 2 entries in the array of 4 elements). The schema and ordering of score type is consistent and has the same pattern for all the students Your help is appreciated.
This is what I am have tried to achieve so far:
DBCursor cursor = collection.find();
try {
while(cursor.hasNext()) {
BasicDBObject doc = (BasicDBObject) cursor.next();
BasicDBList scoreList = (BasicDBList) doc.get("scores");
BasicDBObject hw1 = (BasicDBObject) scoreList.get("2");
double hw1Score = hw1.getDouble("score");
BasicDBObject hw2 = (BasicDBObject) scoreList.get("3");
double hw2Score = hw2.getDouble("score");
if (hw1Score > hw2Score) {
BasicDBObject update = new BasicDBObject("scores.score", hw2Score);
collection.update(doc, new BasicDBObject("$pull",update));
} else {
BasicDBObject update = new BasicDBObject("scores.score", hw1Score);
collection.update(doc, new BasicDBObject("$pull",update));
}
System.out.println(doc);
}
} finally {
cursor.close();
}
}
$pullit?