How to read the arrat data in mongoDB, modify the array data and update the same in mongoDB.
public static void mongoArrayExample(){
DBCursor cursor = null;
MongoClient mongoClient = null;
try {
mongoClient = new MongoClient("localhost", 27017);
DB db = mongoClient.getDB("school");
DBCollection students = db.getCollection("students");
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("_id" , 0);
cursor = students.find(whereQuery);
Map<String, Double> map = new HashMap<String, Double>();
while (cursor.hasNext()){
BasicDBObject result = (BasicDBObject) cursor.next();
BasicDBList scores = (BasicDBList) result.get("scores");
// Reading the data from Array.
for(int j = 0; j< scores.size(); j++)
{
// Reading the individual records
String type = (String) ((BSONObject) scores.get(j)).get("type");
Double score = (Double) ((BSONObject) scores.get(j)).get("score");
if(map.containsKey("homework")){
map.put(type, score);
}
}
}
List<BasicDBObject> scores = new ArrayList<BasicDBObject>();
Set<String> str = map.keySet();
for (String string : str) {
BasicDBObject obje = new BasicDBObject();
obje.put("type", string);
obje.put("score", map.get(string));
scores.add(obje);
}
// Modifying the array
BasicDBObject updateQuery = new BasicDBObject();
updateQuery.append("$set", new BasicDBObject().append("scores", scores));
students.update(whereQuery, updateQuery);
}catch (Exception e) {
}
}