List of usage examples for com.mongodb.client.model Sorts descending
public static Bson descending(final List<String> fieldNames)
From source file:co.aurasphere.mongodb.university.classes.m101j.homework23.MainClass.java
License:Open Source License
/** * The main method.// ww w .j av a 2 s.com * * @param args * the arguments */ public static void main(String[] args) { MongoClient client = new MongoClient(); MongoDatabase numbersDB = client.getDatabase("students"); MongoCollection<Document> grades = numbersDB.getCollection("grades"); // Gets all the grades. MongoCursor<Document> cursor = grades.find(Filters.eq("type", "homework")) .sort(Sorts.ascending("student_id", "score")).iterator(); Object previousStudentId = null; try { // Finds the lowest homework score. while (cursor.hasNext()) { Document entry = cursor.next(); // If the student_id is different from the previous one, this // means that this is the student's lowest graded homework // (they are sorted by score for each student). if (!entry.get("student_id").equals(previousStudentId)) { Object id = entry.get("_id"); grades.deleteOne(Filters.eq("_id", id)); } // The current document ID becomes the new previous one. previousStudentId = entry.get("student_id"); } // Gets the student with the highest average in the class. AggregateIterable<Document> results = grades .aggregate(Arrays.asList(Aggregates.group("$student_id", Accumulators.avg("average", "$score")), Aggregates.sort(Sorts.descending("average")), Aggregates.limit(1))); // There should be only one result. Prints it. System.out.println("Solution : " + results.iterator().next().toJson()); } finally { cursor.close(); } client.close(); }
From source file:co.aurasphere.mongodb.university.classes.m101j.homework31.MainClass.java
License:Open Source License
/** * The main method./* w ww. j a v a2 s .co m*/ * * @param args * the arguments */ @SuppressWarnings("unchecked") public static void main(String[] args) { MongoClient client = new MongoClient(); MongoDatabase db = client.getDatabase("school"); MongoCollection<Document> students = db.getCollection("students"); // Gets all the students. MongoCursor<Document> cursor = students.find().iterator(); try { while (cursor.hasNext()) { Document student = cursor.next(); List<Document> scores = (List<Document>) student.get("scores"); // Finds the lowest homework score. Document minScoreObj = null; double minScore = Double.MAX_VALUE; for (Document scoreDocument : scores) { double score = scoreDocument.getDouble("score"); String type = scoreDocument.getString("type"); // Swaps the scores. if (type.equals("homework") && score < minScore) { minScore = score; minScoreObj = scoreDocument; } } // Removes the lowest score. if (minScoreObj != null) { scores.remove(minScoreObj); } // Updates the record. students.updateOne(Filters.eq("_id", student.get("_id")), new Document("$set", new Document("scores", scores))); } // Gets the student with the highest average in the class. AggregateIterable<Document> results = students.aggregate(Arrays.asList(Aggregates.unwind("$scores"), Aggregates.group("$_id", Accumulators.avg("average", "$scores.score")), Aggregates.sort(Sorts.descending("average")), Aggregates.limit(1))); // There should be only one result. Prints it. System.out.println("Solution : " + results.iterator().next().toJson()); } finally { cursor.close(); } client.close(); }
From source file:com.cognifide.aet.vs.metadata.MetadataDAOMongoDBImpl.java
License:Apache License
@Override public Suite getSuite(DBKey dbKey, String correlationId) throws StorageException { Suite suite = null;// w w w . j a v a 2s.c o m MongoCollection<Document> metadata = getMetadataCollection(dbKey); LOGGER.debug("Fetching suite with correlationId: {} ", correlationId); final FindIterable<Document> found = metadata.find(Filters.eq(CORRELATION_ID_PARAM_NAME, correlationId)) .sort(Sorts.descending(SUITE_VERSION_PARAM_NAME)).limit(1); final Document result = found.first(); if (result != null) { suite = GSON.fromJson(result.toJson(), SUITE_TYPE); } return suite; }
From source file:com.cognifide.aet.vs.metadata.MetadataDAOMongoDBImpl.java
License:Apache License
@Override public Suite getLatestRun(DBKey dbKey, String name) throws StorageException { Suite suite = null;// w w w . j ava 2 s . c om MongoCollection<Document> metadata = getMetadataCollection(dbKey); LOGGER.debug("Fetching latest suite run for company: `{}`, project: `{}`, name `{}`.", dbKey.getCompany(), dbKey.getProject(), name); final FindIterable<Document> found = metadata.find(Filters.eq("name", name)) .sort(Sorts.descending(SUITE_VERSION_PARAM_NAME)).limit(1); final Document result = found.first(); if (result != null) { suite = GSON.fromJson(result.toJson(), SUITE_TYPE); } return suite; }
From source file:com.cognifide.aet.vs.metadata.MetadataDAOMongoDBImpl.java
License:Apache License
@Override public List<Suite> listSuites(DBKey dbKey) throws StorageException { MongoCollection<Document> metadata = getMetadataCollection(dbKey); LOGGER.debug("Fetching all suites for company: `{}`, project: `{}`.", dbKey.getCompany(), dbKey.getProject());/* ww w . j av a 2 s .co m*/ final FindIterable<Document> found = metadata.find().sort(Sorts.descending(SUITE_VERSION_PARAM_NAME)); return FluentIterable.from(found).transform(new Function<Document, Suite>() { @Override public Suite apply(Document result) { return GSON.fromJson(result.toJson(), SUITE_TYPE); } }).toList(); }
From source file:com.egopulse.querydsl.mongodb.MongodbSerializer.java
License:Apache License
public Bson toSort(List<OrderSpecifier<?>> orderBys) { List<Bson> bsons = orderBys.stream().map(orderBy -> { Object key = orderBy.getTarget().accept(this, null); return orderBy.getOrder() == Order.ASC ? Sorts.ascending((String) key) : Sorts.descending((String) key); }).collect(Collectors.toList()); return Sorts.orderBy(bsons); }
From source file:com.github.cherimojava.data.mongo.query.QueryInvocationHandler.java
License:Apache License
private QuerySort addSortInformation(boolean asc) { curQueriedProperty.forEach(parameterProperty -> curSorts.add(parameterProperty.getMongoName())); if (asc) {// w ww . j av a2 s . co m sorts.add(Sorts.ascending(curSorts)); } else { sorts.add(Sorts.descending(curSorts)); } curSorts.clear(); curQueriedProperty.clear(); return querySort.get(); }
From source file:com.px100systems.data.plugin.storage.mongo.MongoDatabaseStorage.java
License:Open Source License
public Long getMaxId(String unitName) { MongoDatabase db = mongoClient.getDatabase(databaseName); Document result = db.getCollection(unitName).find().sort(Sorts.descending("id")) .projection(Projections.include("id")).limit(1).first(); if (result == null) return null; return result.getLong("id"); }
From source file:com.px100systems.data.plugin.storage.mongo.MongoDatabaseStorage.java
License:Open Source License
private Bson orderBy(String s) { boolean descending = false; if (s.toUpperCase().endsWith(" ASC")) { s = s.substring(0, s.length() - " ASC".length()).trim(); descending = false;/*from w w w . ja v a2s .com*/ } else if (s.toUpperCase().endsWith(" DESC")) { s = s.substring(0, s.length() - " DESC".length()).trim(); descending = true; } else s = s.trim(); return descending ? Sorts.descending(s) : Sorts.ascending(s); }
From source file:dto.Dto.java
public String getLastStudentId() { Conexion c = new Conexion(); MongoCollection<Document> col = c.getConnection("usuarios"); Document doc = col.find().sort(Sorts.orderBy(Sorts.descending("_id"))).first(); if (doc == null) { return "0"; } else {//from w ww . j a va 2 s .com return (doc.getString("_id")); } }