mongodb java - Removing an elements from basicdblist -
hi have collection contains around 200 documents looks 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 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");
// here getting list of documents consists of scores array , need remove 3rd elements of , save collection.... how do?
if use loop like
for(int i=0;i<list.size();i++) { list.remove(2);------ gives error here collection.save(obj); } }
are sure can sort 'scores.score'. 'scores' list of objects cant reference objects inside list using dot notation. error should on line.
edit:
dbcursor cursor = collection.find(); while ( cursor.hasnext()) { dbobject dbobject = cursor.next(); basicdblist dblist = (basicdblist) (dbobject.get("score")); //then use java collections.sort() sort list (refer 2 methods @ bottom) dblist.remove(3); collection.save(dbobject); }
use 1 of following sort dblist
1 . using lambda expression
collections.sort(dblist, (o1, o2) -> double.compare(((basicdbobject) o1).getdouble("score"), ((basicdbobject) o2).getdouble("score")));
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; } });
Comments
Post a Comment