0

Hi i have collection which contains around 200 documents looks like e.g

"_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
    }
]

now i wrote code like

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

// Now here i am getting list of documents which consists of an scores array and i need to remove 3rd elements of it and save collection.... but how to do?
if i use for loop like

for(int i=0;i<list.size();i++)
{
list.remove(2);------ it gives an error here 
collection.save(obj);
}
}
Divya Bhaloidiya
  • 5,018
  • 2
  • 25
  • 45
anand24
  • 11
  • 2

1 Answers1

2

Are you sure that you can sort it as 'scores.score'. As 'scores' is a list of objects you cant reference objects inside list using dot notation. Error should be on that line.

Edit:

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

Use one of the following to sort the DBList
1 . Using Lambda expression

    Collections.sort(dbList, (o1, o2) -> Double.compare(((BasicDBObject) o1).getDouble("score"), ((BasicDBObject) o2).getDouble("score")));    
  1. or 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;    
    }    
    });    
    
Isuru
  • 700
  • 9
  • 22
  • 1
    This seems more like a comment. If you have a suggested solution, please add your solution more clearly in this answer. – ptd Jan 25 '15 at 14:47