简体   繁体   English

Mongodb:从文档中拉出子文档

[英]Mongodb : Pull out subdocument from a document

My database schema looks like this: 我的数据库架构如下所示:

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

The questions asks us to remove the lowest homework score for each student. 这些问题要求我们删除每个学生的最低家庭作业分数。 My approach is: 我的方法是:

  • first get a list of documents containing only ids and homework scores of students. 首先获得一份仅包含学生证件和作业成绩的文件清单。
  • Get the minimum hw score of each student. 获得每个学生的最低硬件分数。
  • Pull out the subdocument containing that minimum homework score. 拉出包含最低作业分数的子文档。

My prints correctly show me min homework score for each student but my pull query is not removing the values from database. 我的打印正确地显示了每个学生的最低作业成绩,但我的下拉查询未从数据库中删除这些值。 What am I missing here? 我在这里想念什么? Not asking for solution, just a hint as to what I am doing wrong here would help. 不要求解决方案,只是暗示我在这里做错了会有所帮助。 Thanks. 谢谢。

Small correction needed in your code, you are trying to remove 您的代码中需要进行小的更正,因此您尝试删除

{"scores.type":"homework", "scores.score":"whatever"} {“ scores.type”:“作业”,“ scores.score”:“任何内容”}

and you should remove subdocument 并且您应该删除子文档

{"type":"homework", "score":"..."} {“ type”:“家庭作业”,“ score”:“ ...”}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM