List of usage examples for com.mongodb.client.model Filters eq
public static <TItem> Bson eq(final String fieldName, @Nullable final TItem value)
From source file:co.aurasphere.mongodb.university.classes.m101j.homework23.MainClass.java
License:Open Source License
/** * The main method./*from w w w . j ava 2 s . c o m*/ * * @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.//from w ww . j a va 2 s .c o 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:codeu.chat.database.Database.java
License:Apache License
public boolean removeMessage(String id) { boolean result; try {/* w ww . j ava 2 s . co m*/ result = messages.deleteOne(Filters.eq("id", id)).getDeletedCount() == 1 ? true : false; } catch (MongoWriteException e) { return false; } return result; }
From source file:codeu.chat.database.Database.java
License:Apache License
public boolean removeConversation(String id) { boolean result; try {/*from w w w . j a va 2s .c o m*/ result = conversations.deleteOne(Filters.eq("id", id)).getDeletedCount() == 1 ? true : false; } catch (MongoWriteException e) { return false; } return result; }
From source file:codeu.chat.database.Database.java
License:Apache License
public boolean removeUser(String id) { boolean result; try {/* w w w. j a va 2 s . co m*/ result = users.deleteOne(Filters.eq("id", id)).getDeletedCount() == 1 ? true : false; } catch (MongoWriteException e) { return false; } return result; }
From source file:codeu.chat.server.Server.java
License:Apache License
public User login(String username, String password) { LOG.info("Logging in " + username); Iterable<Document> foundDocs = database.users.find(Filters.eq("name", username)); LOG.info("Found user"); for (Document doc : foundDocs) { System.out.println(doc);// w w w . j av a2 s. c o m if (password.equals(doc.get("password"))) { LOG.info("Successfully logged in " + username); return Packer.unpackUser(doc); } } return null; }
From source file:com.avbravo.ejbjmoordb.mongodb.repository.Repository.java
/** * implementa replaceOne/*from w w w . j av a2 s . co m*/ * * @param key * @param value * @param docUpdate * @return */ public Integer replaceOne(String key, String value, Document docUpdate) { Integer documentosModificados = 0; try { UpdateResult updateResult = getMongoDatabase().getCollection(collection) .replaceOne(Filters.eq(key, value), docUpdate); return (int) updateResult.getModifiedCount(); } catch (Exception e) { Logger.getLogger(Repository.class.getName() + "replaceOne()").log(Level.SEVERE, null, e); exception = new Exception("replaceOne() ", e); } return 0; }
From source file:com.avbravo.ejbjmoordb.mongodb.repository.Repository.java
/** * Crea un filtro para filtrar entre fechas * * @param startname/* w w w . jav a 2 s .co m*/ * @param datestart * @param endname * @param datelimit * * @return */ public List<T> filterBetweenDate(String secondaryfield, String secondaryfieldvalue, String fieldnamestart, Date datestartvalue, String fieldlimitname, Date datelimitvalue, Document... docSort) { list = new ArrayList<>(); try { Document sortQuery = new Document(); if (docSort.length != 0) { sortQuery = docSort[0]; } Bson filter = Filters.and(Filters.eq(secondaryfield, secondaryfieldvalue), Filters.gte(fieldnamestart, datestartvalue), Filters.lte(fieldlimitname, datelimitvalue)); list = filters(filter, sortQuery); } catch (Exception e) { Logger.getLogger(Repository.class.getName() + "filterBetweenDate()").log(Level.SEVERE, null, e); exception = new Exception("filterBetweenDate() ", e); } return list; }
From source file:com.avbravo.ejbjmoordb.mongodb.repository.Repository.java
/** * Crea un filtro para filtrar entre fechas * * @param startname/*from w ww . j av a 2s . c o m*/ * @param datestart * @param endname * @param datelimit * * @return */ public List<T> filterBetweenDate(String secondaryfield, Integer secondaryfieldvalue, String fieldnamestart, Date datestartvalue, String fieldlimitname, Date datelimitvalue, Document... docSort) { list = new ArrayList<>(); try { Document sortQuery = new Document(); if (docSort.length != 0) { sortQuery = docSort[0]; } Bson filter = Filters.and(Filters.eq(secondaryfield, secondaryfieldvalue), Filters.gte(fieldnamestart, datestartvalue), Filters.lte(fieldlimitname, datelimitvalue)); list = filters(filter, sortQuery); } catch (Exception e) { Logger.getLogger(Repository.class.getName() + "filterBetweenDate()").log(Level.SEVERE, null, e); exception = new Exception("filterBetweenDate() ", e); } return list; }
From source file:com.avbravo.ejbjmoordb.mongodb.repository.Repository.java
/** * Crea un filtro para filtrar entre fechas * * @param startname/* w w w . j av a 2 s . c o m*/ * @param datestart * @param endname * @param datelimit * * @return */ public List<T> filterBetweenDatePagination(String secondaryfield, String secondaryfieldvalue, String fieldnamestart, Date datestartvalue, String fieldlimitname, Date datelimitvalue, Integer pageNumber, Integer rowsForPage, Document... docSort) { list = new ArrayList<>(); try { Document sortQuery = new Document(); if (docSort.length != 0) { sortQuery = docSort[0]; } Bson filter = Filters.and(Filters.eq(secondaryfield, secondaryfieldvalue), Filters.gte(fieldnamestart, datestartvalue), Filters.lte(fieldlimitname, datelimitvalue)); list = filtersPagination(filter, pageNumber, rowsForPage, sortQuery); } catch (Exception e) { Logger.getLogger(Repository.class.getName() + "filterBetweenDatePagination()").log(Level.SEVERE, null, e); exception = new Exception("filterBetweenDatePagination ", e); } return list; }