Search code examples
javamongodbsubdocument

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.


Solution

  • Small correction needed in your code, you are trying to remove

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

    and you should remove subdocument

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