List of usage examples for com.mongodb.client MongoCursor hasNext
@Override
boolean hasNext();
From source file:br.edu.ifpb.bdnc.mongodb.DataHoraMongo.java
public DataHora read(int codvenda) { MongoCursor<Document> cursor = collection.find(eq("_id", codvenda)); DataHora datahora = null;//w ww .jav a2 s . com if (cursor.hasNext()) { datahora = new DataHora().fromDocument(cursor.next()); } return datahora; }
From source file:br.edu.ifpb.bdnc.mongodb.ValorTotalMongo.java
public ValorTotal read(int vendaid) { MongoCursor<Document> cursor = collection.find(eq("_id", vendaid)); ValorTotal total = null;//from ww w . j a v a 2 s .c o m if (cursor.hasNext()) { total = new ValorTotal().fromDocument(cursor.next()); } return total; }
From source file:br.edu.ifpb.bdnc.start.write.dao.mongo.PaginaVendaDaoMongo.java
@Override public ArrayList<Pagina> get(String dono) { ArrayList<Pagina> paginas = new ArrayList(); MongoCursor cursor = database.find(eq("dono", dono)).iterator(); while (cursor.hasNext()) { Document doc = (Document) cursor.next(); PaginaVenda pagina = new PaginaVenda(); paginas.add(pagina.fromDocument(doc)); }/*w w w . j ava 2s .co m*/ System.out.println(paginas); return paginas; }
From source file:co.aurasphere.mongodb.university.classes.m101j.homework23.MainClass.java
License:Open Source License
/** * The main method./*from w w w . j a va 2s .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.//from ww w . j av a 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:co.edu.uniandes.bigdata.ProyectoBigData.logica.TwitterColombiaLogica.java
public List<MongoDataRecord> getMongoFunctionResults(String functionStringWithParameters, int limitResults) { Document docMongo = mongoDB.runCommand(new Document("$eval", functionStringWithParameters)); String collectionResults = docMongo.getString("retval"); MongoCursor cursor = mongoDB.getCollection(collectionResults).find().sort(new Document("_id.date", 1)) .limit(limitResults).iterator(); List<MongoDataRecord> mongoResults = new ArrayList<>(); while (cursor.hasNext()) { String resultString = cursor.next().toString(); // obtener propiedades del resultado String hashtag = getValueFromMongoResult(resultString, "hashtag", false), user = getValueFromMongoResult(resultString, "user", false), date = getValueFromMongoResult(resultString, "date", false), sentiment = getValueFromMongoResult(resultString, "sentiment", false); Double tweets = Double.parseDouble(getValueFromMongoResult(resultString, "totalTweets", true)), retweets = Double.parseDouble(getValueFromMongoResult(resultString, "totalReTweet", true)), followers = Double.parseDouble(getValueFromMongoResult(resultString, "totalFollowers", true)); mongoResults.add(new MongoDataRecord(hashtag, user, date, sentiment, tweets, retweets, followers)); System.out.println(hashtag + "|" + user + "|" + date + "|" + sentiment + "|" + tweets + "|" + retweets + "|" + followers); }/*from w w w .ja va 2 s .co m*/ return mongoResults; }
From source file:codeu.chat.server.Model.java
License:Apache License
/** * Restores account information from the database. *//*from w ww . jav a2 s . c o m*/ public void syncModel() { MongoCursor<Document> cursor = collection.find().iterator(); try { while (cursor.hasNext()) { final Document next = cursor.next(); final String rawID = (String) next.get("id"); final String realID = rawID.substring(rawID.indexOf(':') + 1, rawID.indexOf(']') - 1); final User user = new User(Uuid.parse(realID), (String) next.get("username"), Time.fromMs((long) next.get("time"))); usernameSalt.put(user.name, (String) next.get("salt")); usernamePassword.put(user.name, (String) next.get("password")); userById.insert(user.id, user); userByTime.insert(user.creation, user); userByText.insert(user.name, user); } } catch (Exception e) { System.out.println("data error: unable to parse database info"); } finally { cursor.close(); } }
From source file:com.acmeair.mongo.services.FlightServiceImpl.java
License:Apache License
@Override protected List<String> getFlightBySegment(String segment, Date deptDate) { try {// ww w. j av a 2 s . co m JSONObject segmentJson = (JSONObject) new JSONParser().parse(segment); MongoCursor<Document> cursor; if (deptDate != null) { if (logger.isLoggable(Level.FINE)) { logger.fine("getFlghtBySegment Search String : " + new BasicDBObject("flightSegmentId", segmentJson.get("_id")) .append("scheduledDepartureTime", deptDate).toJson()); } cursor = flight.find(new BasicDBObject("flightSegmentId", segmentJson.get("_id")) .append("scheduledDepartureTime", deptDate)).iterator(); } else { cursor = flight.find(eq("flightSegmentId", segmentJson.get("_id"))).iterator(); } List<String> flights = new ArrayList<String>(); try { while (cursor.hasNext()) { Document tempDoc = cursor.next(); if (logger.isLoggable(Level.FINE)) { logger.fine("getFlghtBySegment Before : " + tempDoc.toJson()); } Date deptTime = (Date) tempDoc.get("scheduledDepartureTime"); Date arvTime = (Date) tempDoc.get("scheduledArrivalTime"); tempDoc.remove("scheduledDepartureTime"); tempDoc.append("scheduledDepartureTime", deptTime.toString()); tempDoc.remove("scheduledArrivalTime"); tempDoc.append("scheduledArrivalTime", arvTime.toString()); if (logger.isLoggable(Level.FINE)) { logger.fine("getFlghtBySegment after : " + tempDoc.toJson()); } flights.add(tempDoc.append("flightSegment", segmentJson).toJson()); } } finally { cursor.close(); } return flights; } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } }
From source file:com.bdnc.ecommercebdnc.dao.DAODocumentos.java
public List<Compra> buscarCompras() { MongoClient client = new MongoClient("localhost", 27017); MongoDatabase dataBase = client.getDatabase("ecommerce-bdnc"); MongoCollection<Document> collection = dataBase.getCollection("vendas"); List<Compra> compras = new ArrayList<>(); MongoCursor<Document> cursor = collection.find().iterator(); while (cursor.hasNext()) { Compra compra = new Compra(); compras.add(compra.fromDocument(cursor.next())); }/*from w w w . j av a2s .c o m*/ client.close(); return compras; }
From source file:com.chadcover.Homework_23.java
License:Apache License
public static void main(String[] args) { MongoClient client = new MongoClient(); MongoDatabase database = client.getDatabase("students"); MongoCollection<Document> collection = database.getCollection("gradesBak"); long count = collection.count(); System.out.println(count);//from w w w .j a v a 2 s. c o m Bson filter = eq("type", "homework"); Bson sort = ascending("student_id", "score"); Bson projection = fields(include("student_id", "score")); // better for large datasets MongoCursor<Document> result = collection.find(filter).sort(sort).projection(projection).iterator(); try { int lastId = 0; int counter = 0; while (result.hasNext()) { Document cur = result.next(); int id = (Integer) cur.get("student_id"); // when moving to new student // delete that record, which is the lowest homework score if (id != lastId || counter == 0) { double grade = (Double) cur.get("score"); System.out.println("Delete this score: " + grade); collection.deleteOne(eq("_id", cur.get("_id"))); } else { // do nothing } lastId = id; counter++; } } finally { result.close(); } }