Created
January 18, 2018 18:45
-
-
Save gegen07/0737b81373db4623c19b6fa22dce679e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Copy and Paste this snippet and solve your homework 2.3 of Mongo course for Java Developers. | |
* Remember to import all libraries before you use. | |
* This project is handled by Maven so you have to use Maven too with the dependency of MongoJavaDriver | |
* | |
* Created By gegen07 | |
*/ | |
public class App { | |
public static void main( String[] args ) { | |
MongoClient client = new MongoClient("localhost", 27017); | |
MongoDatabase db = client.getDatabase("students"); | |
MongoCollection<Document> grades = db.getCollection("grades"); | |
Bson filter = eq("type", "homework"); | |
Bson projection = fields(include("student_id", "score")); | |
Bson sort = orderBy(ascending("student_id"), descending("score")); | |
List<Document> cursor = grades.find(filter) | |
.sort(sort) | |
.projection(projection) | |
.into(new ArrayList<Document>()); | |
removeLowest(grades, cursor); | |
} | |
private static void removeLowest(MongoCollection grades, List<Document> cursor) { | |
ObjectId _id = null; | |
Integer id; | |
id = cursor.get(0).getInteger("student_id"); | |
for (Document doc: cursor) { | |
int aux = doc.getInteger("student_id"); | |
if (id != aux) { | |
id = doc.getInteger("student_id"); | |
grades.deleteOne(new Document("_id", _id)); | |
} | |
_id = doc.getObjectId("_id"); | |
} | |
grades.deleteOne(new Document("_id", _id)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment