使用Java API在mongodb中获取值数组

时间:2015-01-24 16:37:43

标签: java arrays mongodb list

我需要使用Java获取文档中数组的值:

{
   "_id" : 11,
   "name" : "Marcus Blohm",
   "scores" : [
    {
        "type" : "exam",
        "score" : 78.42617835651868
    },
    {
        "type" : "quiz",
        "score" : 82.58372817930675
    },
    {
        "type" : "homework",
        "score" : 87.49924733328717
    },
    {
         "type" : "homework",
         "score" : 15.81264595052612
    }
   ]
}

我无法获得"type" = "homework"的最小值。我喜欢在数组中获取这些值,然后在java中使用它。

有人有想法吗?

我的实际代码是:

           BasicDBObject query=new BasicDBObject("scores.type","homework");
     //       BasicDBObject fields=new BasicDBObject("scores.$", 1);
            //DBCursor cursor = table.find(filtro).sort(sortOrder);
            // Este objeto hace la ordenación que nosinteresa
             BasicDBObject sortOrder=new BasicDBObject();
             sortOrder.put("_id",1);             
             sortOrder.put("scores.type",1);
             sortOrder.put("scores.score",1);

             DBCursor cursor = table.find(query).sort(sortOrder);


    try {

               while (cursor.hasNext()) {
                  //  DBObject cur = cursor.next();                   

                  //  System.out.println(cur);
                  // Con el código comentado borramos todo el documento      
                  //      table.remove(cur);              

                    BasicDBList e = (BasicDBList) cursor.next().get("scores");
                    System.out.println(e);

               }
               } finally {
                    cursor.close();
                    mongoClient.close();
               }

} catch (UnknownHostException ex) {
         System.out.println("Hemos tenido algún problema con MongoDB");
        }

由于

1 个答案:

答案 0 :(得分:0)

这可以工作并更新数组:

DBCursor cursor = collection.find();

while (cursor.hasNext()) {

     DBObject dbObject1 = cursor.next();
     BasicDBList scores = (BasicDBList) dbObject1.get("scores");
     DBObject o1 = (DBObject) scores.get(2);
     DBObject o2 = (DBObject) scores.get(3);

     BasicDBObject match = new BasicDBObject("_id", dbObject1.get("_id"));
     BasicDBObject select;
     if ((Double) o1.get("score") <= (Double) o2.get("score")) {
            select = new BasicDBObject("scores", o1);
     } else {
            select = new BasicDBObject("scores", o2);
     }

     collection.update(match, new BasicDBObject("$pull", select));
}