package com.tengen;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.mongodb.AggregationOutput;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
public class Homework23 {
public static void main(String[] args) throws UnknownHostException {
MongoClient client = new MongoClient(new ServerAddress("localhost",
27017));
DB db = client.getDB("students");
DBCollection collection = db.getCollection("grades");
BasicDBObject bdb = new BasicDBObject("type", "homework");
BasicDBObject sort = new BasicDBObject("student_id", 1).append("score",
1);
// DBCursor cur = collection.find(bdb).sort(sort);
List<DBObject> pipeline = new ArrayList<DBObject>();
pipeline.add(new BasicDBObject("$group", new BasicDBObject("_id",
"$student_id")));
AggregationOutput aoup = collection.aggregate(pipeline);
Iterable<DBObject> results = aoup.results();
Iterator<DBObject> itr = results.iterator();
DBCursor cur = null;
try {
while (itr.hasNext()) {
DBObject agdb = itr.next();
bdb.append("student_id", agdb.get("_id"));
cur = collection.find(bdb).sort(sort);
cur.hasNext();
DBObject docToRemove = cur.next();
Double minScore = (Double) docToRemove.get("score");
while (cur.hasNext()) {
DBObject doc1 = cur.next();
if (minScore > (Double) doc1.get("score")) {
minScore = (Double) doc1.get("score");
docToRemove = doc1;
}
}
System.out.println("*********************");
System.out.println(docToRemove);
System.out.println("*********************");
collection.remove(docToRemove);
}
}
finally {
if (cur != null)
cur.close();
}
}
}