0

嗨,我有一个包含大约 200 个文档的集合,例如

"_id": 0,
"name": "Demarcus Audette",
"scores": [
    {
        "type": "exam",
        "score": 30.61740640636871
    },
    {
        "type": "quiz",
        "score": 14.23233821353732
    },
    {
        "type": "homework",
        "score": 31.41421298576332
    },
    {
        "type": "homework",
        "score": 30.09304792394713
    }
]

现在我写了这样的代码

DBCursor cursor = collection.find().sort(new BasicDBObject("scores.score":1));
while( cursor.hasNext() )
{
DBobject obj=cursor.next();
BasicDBList list=(BasicDBList) Bobj.get("scores");

// 现在我在这里获取包含分数数组的文档列表,我需要删除它的第三个元素并保存集合....但是怎么办?
如果我使用 for 循环

for(int i=0;i<list.size();i++)
{
list.remove(2);------ it gives an error here 
collection.save(obj);
}
}
4

2 回答 2

1

您确定可以将其排序为“scores.score”。由于“分数”是一个对象列表,因此您无法使用点符号引用列表中的对象。错误应该在那条线上。

编辑:

DBCursor cursor = collection.find();    
while ( cursor.hasNext()) {    
    DBObject dbObject = cursor.next();    
    BasicDBList dbList = (BasicDBList) (dbObject.get("score"));    

    //then use java Collections.sort() to sort the List (refer to two methods at the bottom)   

    dbList.remove(3);    
    collection.save(dbObject);    
}    

使用以下方法之一对 DBList
1 进行排序。使用 Lambda 表达式

    Collections.sort(dbList, (o1, o2) -> Double.compare(((BasicDBObject) o1).getDouble("score"), ((BasicDBObject) o2).getDouble("score")));    
  1. 或 java 7 <

    Collections.sort(dbList, new Comparator<Object>() {      
        public int compare(Object o, Object o2) {    
        if (((BasicDBObject) o).getDouble("score") >= ((BasicDBObject) o2).getDouble("score")) {    
            return 1;    
        }    
        return -1;    
    }    
    });    
    
于 2015-01-25T14:28:14.833 回答
0

请参阅此链接https://gist.github.com/machadolucas/5188447/raw/e3f5c44c2be756c6087809df63f7ea8f4682ace9/Mongo3_1.java 我一直是[发布此消息的一些符号)))]

于 2013-08-19T20:41:58.477 回答