java - 蒙戈数据库 : Pull out subdocument from a document

标签 java mongodb subdocument

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

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

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

  • 首先获取仅包含 ids 和作业分数的文档列表 学生的。
  • 获取每个学生的最低硬件分数。
  • 找出包含最低作业分数的子文档。

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

最佳答案

您的代码中需要进行一些小修正,您正在尝试删除

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

并且您应该删除子文档

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

关于java - 蒙戈数据库 : Pull out subdocument from a document,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33470631/

相关文章:

mongodb - GORM for MongoDB:衍生属性(property)?

java - Java 中等效的 ASP.NET 母版页

java - 代码模型 : how to check if I need to generate a generic type?

java - 直接编码/解码不会产生原始数据

linux - 暂时将 fork 的 mongod 进程的 stdout/stderr 路由到控制台

node.js - 动态更新 MongoDB 数组的索引

javascript - 如何使用 Mongoose 的 addToSet 添加多个 ObjectId?

node.js - Mongoose - 链接到同一类型的嵌套子文档

java - 在 JVM 上禁用本地 JMX 连接

mongodb - 在 MongoDB 中,何时使用简单的子文档,何时使用具有 2 字段元素的数组?