List of usage examples for com.mongodb.client MongoCursor close
@Override
void close();
From source file:SelectItemController.java
@Override public void initialize(URL url, ResourceBundle rb) { MongoCursor<Document> cursor4 = db.getCollection("ItemDetail").find().iterator(); try {/* w w w. j av a 2s.co m*/ while (cursor4.hasNext()) { String rs = cursor4.next().getString("ItemName"); ItemList.getItems().addAll(rs); } } finally { cursor4.close(); } }
From source file:actor4j.core.persistence.connectors.MongoDBPersistenceAdapter.java
License:Open Source License
@Override public void receive(ActorMessage<?> message) { if (message.tag == PERSIST_EVENTS) { try {/*w w w. j a v a2 s. c om*/ JSONArray array = new JSONArray(message.valueAsString()); if (array.length() == 1) { Document document = Document.parse(array.get(0).toString()); events.insertOne(document); } else { List<WriteModel<Document>> requests = new ArrayList<WriteModel<Document>>(); for (Object obj : array) { Document document = Document.parse(obj.toString()); requests.add(new InsertOneModel<Document>(document)); } events.bulkWrite(requests); } parent.send(new ActorMessage<Object>(null, INTERNAL_PERSISTENCE_SUCCESS, self(), message.source)); } catch (Exception e) { e.printStackTrace(); parent.send(new ActorMessage<Exception>(e, INTERNAL_PERSISTENCE_FAILURE, self(), message.source)); } } else if (message.tag == PERSIST_STATE) { try { Document document = Document.parse(message.valueAsString()); states.insertOne(document); parent.send(new ActorMessage<Object>(null, INTERNAL_PERSISTENCE_SUCCESS, self(), message.source)); } catch (Exception e) { e.printStackTrace(); parent.send(new ActorMessage<Exception>(e, INTERNAL_PERSISTENCE_FAILURE, self(), message.source)); } } else if (message.tag == RECOVER) { try { JSONObject obj = new JSONObject(); Document document = null; FindIterable<Document> statesIterable = states .find(new Document("persistenceId", message.valueAsString())) .sort(new Document("timeStamp", -1)).limit(1); document = statesIterable.first(); if (document != null) { JSONObject stateValue = new JSONObject(document.toJson()); stateValue.remove("_id"); long timeStamp = stateValue.getJSONObject("timeStamp").getLong("$numberLong"); stateValue.put("timeStamp", timeStamp); obj.put("state", stateValue); FindIterable<Document> eventsIterable = events .find(new Document("persistenceId", message.valueAsString()).append("timeStamp", new Document("$gte", timeStamp))) .sort(new Document("timeStamp", -1)); JSONArray array = new JSONArray(); MongoCursor<Document> cursor = eventsIterable.iterator(); while (cursor.hasNext()) { document = cursor.next(); JSONObject eventValue = new JSONObject(document.toJson()); eventValue.remove("_id"); timeStamp = eventValue.getJSONObject("timeStamp").getLong("$numberLong"); eventValue.put("timeStamp", timeStamp); array.put(eventValue); } cursor.close(); obj.put("events", array); } else obj.put("state", new JSONObject()); parent.send(new ActorMessage<String>(obj.toString(), INTERNAL_PERSISTENCE_RECOVER, self(), message.source)); } catch (Exception e) { e.printStackTrace(); JSONObject obj = new JSONObject(); obj.put("error", e.getMessage()); parent.send(new ActorMessage<String>(obj.toString(), INTERNAL_PERSISTENCE_RECOVER, self(), message.source)); } } }
From source file:co.aurasphere.mongodb.university.classes.m101j.homework23.MainClass.java
License:Open Source License
/** * The main method./* w ww . j av a 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.//w w w .j a va 2s. c om * * @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.server.Model.java
License:Apache License
/** * Restores account information from the database. *///from ww w.j a v a 2 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 {/*www. j a va2s . c om*/ 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.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);/*w w w . ja 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(); } }
From source file:com.github.terma.fastselect.benchmark.PlayerMongoDb.java
License:Apache License
@Override public Object groupByWhereSimple() throws Exception { MongoCollection collection = database.getCollection("myCollection"); MongoCursor<Document> cursor = collection .aggregate(Arrays.asList(Document.parse("{$match: {\"prr\": 1}}"), Document.parse("{$group: {_id: {prg: \"$prg\", prr: \"$prr\"}, count: {$sum: 1}}}"))) .iterator();/* w w w . j a v a 2s . c om*/ Map<Integer, Map<Integer, Integer>> g = new HashMap<>(); groupBy(g, cursor); cursor.close(); return g; }
From source file:com.github.terma.fastselect.benchmark.PlayerMongoDb.java
License:Apache License
@Override public Object groupByWhereManySimple() throws Exception { MongoCollection collection = database.getCollection("myCollection"); MongoCursor<Document> cursor = collection .aggregate(Arrays.asList(Document.parse("{$match: {\"prr\": 1, \"prg\": 89, \"csg\": 50}}"), Document.parse("{$group: {_id: {prg: \"$prg\", prr: \"$prr\"}, count: {$sum: 1}}}"))) .iterator();//from w ww . j a v a 2 s.com Map<Integer, Map<Integer, Integer>> g = new HashMap<>(); groupBy(g, cursor); cursor.close(); return g; }
From source file:com.github.terma.fastselect.benchmark.PlayerMongoDb.java
License:Apache License
@Override public Object groupByWhereIn() throws Exception { MongoCollection collection = database.getCollection("myCollection"); MongoCursor<Document> cursor = collection .aggregate(Arrays.asList( Document.parse("{$match: {\"prr\": {$in: [" + DemoData.SCALAR_IN_2_AS_STRING + "]}}}"), Document.parse("{$group: {_id: {prg: \"$prg\", prr: \"$prr\"}, count: {$sum: 1}}}"))) .iterator();/* w w w. j a v a2 s . c o m*/ Map<Integer, Map<Integer, Integer>> g = new HashMap<>(); groupBy(g, cursor); cursor.close(); return g; }