我的数据库架构如下所示:
{
"_id" : 137,
"name" : "Tamika Schildgen",
"scores" : [
{
"score" : 4.433956226109692,
"type" : "exam"
},
{
"type" : "quiz",
"score" : 65.50313785402548
},
{
"type" : "homework",
"score" : 89.5950384993947
},
{
"type" : "homework",
"score" : 54.75994689226145
}
]
}
Bson filter = (Filters.eq("scores.type", "homework"));
Bson projection = Projections.slice("scores", 2, 2);
Bson sort = Sorts.ascending("_id");
List<Document> all = collection.find(filter).projection(projection).sort(sort).into(new ArrayList<Document>());
for (Document cur : all) {
List<Document> score = (List<Document>) cur.get("scores");
List marks = new ArrayList<Integer>();
for (Document hw1 : score) {
marks.add(hw1.get("score"));
}
Collections.sort(marks);
double x = (Double) marks.get(0);
Bson find = Filters.eq("_id", cur.get("_id"));
Bson update = new Document("$pull", new Document("scores", new Document("scores.type", "homework").append("scores.score" , x)));
collection.updateOne(find,update);
System.out.println("deleted " + cur.get("_id") + " " + x);
问题要求我们删除每个学生的最低作业成绩。我的方法是:
我的打印正确显示每个学生的最小作业分数,但我的拉查询不是从数据库中删除值。我在这里错过了什么? 不要求解决方案,只是暗示我在这里做错了什么会有所帮助。谢谢。
答案 0 :(得分:0)
代码中需要进行小幅修正,您正试图删除
{“scores.type”:“homework”,“scores.score”:“whatever”}
你应该删除子文档
{“type”:“homework”,“score”:“...”}