package db_operations import com mongodb import java net UnknownHostEx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package db_operations;
import com.mongodb.*;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Map;
/**
* Created by Kell on 31.03.14.
*/
public class StudentDataOperations {
Mongo mongoClient;
DB db;
public void deleteMinScores() {
DBCollection studsCollection = db.getCollection("students");
DBCursor studsCursor = studsCollection.find();
BasicDBObject minScore;
try {
for (int i = 0; studsCursor.hasNext(); i++) {
DBObject cur = studsCursor.next();
minScore = getMinScore((ArrayList) cur.get("scores"));
studsCollection.update(new BasicDBObject("_id", i),
new BasicDBObject("$pull", new BasicDBObject("scores", minScore)));
}
} finally {
studsCursor.close();
}
}
public BasicDBObject getMinScore(ArrayList scores) {
int scoresSize = scores.size();
double curNumScore = 0;
double minNumScore = 0;
BasicDBObject minScore = new BasicDBObject((Map) scores.get(0));
for (int i = 1; i < scoresSize; i++) {
curNumScore = Double.parseDouble(((BasicDBObject) scores.get(i)).get("score").toString());
minNumScore = Double.parseDouble(minScore.get("score").toString());
if (curNumScore < minNumScore) {
minScore = new BasicDBObject((Map) scores.get(i));
}
}
return minScore;
}
public StudentDataOperations() throws UnknownHostException {
try {
this.mongoClient = new Mongo();
this.db = mongoClient.getDB("school");
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}