Mongodb : 从文档中拉出子文档

Mongodb : Pull out subdocument from a document

我的数据库架构如下所示:

{
"_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);

这些问题要求我们删除每个学生的最低家庭作业分数。我的做法是:

我的打印件正确地显示了每个学生的最低家庭作业分数,但我的拉取查询没有从数据库中删除值。我在这里错过了什么? 不要求解决方案,只是提示我在这里做错了什么会有所帮助。谢谢。

您的代码需要稍作更正,您正在尝试删除

{"scores.type":"homework", "scores.score":"whatever"}

你应该删除子文档

{"type":"homework", "score":"..."}