从basicdblist中删除元素

时间:2013-08-16 06:25:13

标签: mongodb-java

您好我的收藏品包含大约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");

//现在我在这里得到包含得分数组的文档列表,我需要删除它的第3个元素并保存收集....但该怎么做?
 如果我使用像

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

2 个答案:

答案 0 :(得分: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&lt;

    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;    
    }    
    });    
    

答案 1 :(得分:0)

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

相关问题