List of usage examples for com.mongodb MongoClient close
public void close()
From source file:mongodb_teste.Jmongo.java
private void jBinsertMatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBinsertMatActionPerformed // TODO add your handling code here: MongoClient mongoClient = new MongoClient(); MongoDatabase db = mongoClient.getDatabase("BDprject"); db.getCollection("Professores").updateOne(new Document("nome", jMatInNomeProf.getText()), new Document("$push", new Document("materias", new Document("nome", jMatInNome.getText()).append("nota", jMatInNota.getText())))); JOptionPane.showMessageDialog(null, "Inserido com sucesso"); mongoClient.close(); }
From source file:mongoSample.MongoSample.java
License:Apache License
/** * Run this main method to see the output of this quick example. * * @param args//from www.jav a2 s . co m * takes an optional single argument for the connection string */ public static void main(final String[] args) { String mongoServer = args[0]; MongoClient mongoClient = new MongoClient(mongoServer); MongoDatabase database = mongoClient.getDatabase("sakila"); MongoCollection<Document> collection = database.getCollection("test"); // drop all the data in it collection.drop(); // make a document and insert it Document doc = new Document("name", "MongoDB").append("type", "database").append("count", 1).append("info", new Document("x", 203).append("y", 102)); collection.insertOne(doc); // get it (since it's the only one in there since we dropped the rest // earlier on) Document myDoc = collection.find().first(); System.out.println(myDoc.toJson()); // now, lets add lots of little documents to the collection so we can // explore queries and cursors List<Document> documents = new ArrayList<Document>(); for (int i = 0; i < 100; i++) { documents.add(new Document("i", i)); } collection.insertMany(documents); System.out.println( "total # of documents after inserting 100 small ones (should be 101) " + collection.count()); // find first myDoc = collection.find().first(); System.out.println(myDoc); System.out.println(myDoc.toJson()); // lets get all the documents in the collection and print them out MongoCursor<Document> cursor = collection.find().iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); } for (Document cur : collection.find()) { System.out.println(cur.toJson()); } // now use a query to get 1 document out myDoc = collection.find(eq("i", 71)).first(); System.out.println(myDoc.toJson()); // now use a range query to get a larger subset cursor = collection.find(gt("i", 50)).iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); } // range query with multiple constraints cursor = collection.find(and(gt("i", 50), lte("i", 100))).iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); } // Query Filters myDoc = collection.find(eq("i", 71)).first(); System.out.println(myDoc.toJson()); // now use a range query to get a larger subset Block<Document> printBlock = new Block<Document>() { @Override public void apply(final Document document) { System.out.println(document.toJson()); } }; collection.find(gt("i", 50)).forEach(printBlock); // filter where; 50 < i <= 100 collection.find(and(gt("i", 50), lte("i", 100))).forEach(printBlock); // Sorting myDoc = collection.find(exists("i")).sort(descending("i")).first(); System.out.println(myDoc.toJson()); // Projection myDoc = collection.find().projection(excludeId()).first(); System.out.println(myDoc.toJson()); // Update One collection.updateOne(eq("i", 10), new Document("$set", new Document("i", 110))); // Update Many UpdateResult updateResult = collection.updateMany(lt("i", 100), new Document("$inc", new Document("i", 100))); System.out.println(updateResult.getModifiedCount()); // Delete One collection.deleteOne(eq("i", 110)); // Delete Many DeleteResult deleteResult = collection.deleteMany(gte("i", 100)); System.out.println(deleteResult.getDeletedCount()); collection.drop(); // ordered bulk writes List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>(); writes.add(new InsertOneModel<Document>(new Document("_id", 4))); writes.add(new InsertOneModel<Document>(new Document("_id", 5))); writes.add(new InsertOneModel<Document>(new Document("_id", 6))); writes.add( new UpdateOneModel<Document>(new Document("_id", 1), new Document("$set", new Document("x", 2)))); writes.add(new DeleteOneModel<Document>(new Document("_id", 2))); writes.add(new ReplaceOneModel<Document>(new Document("_id", 3), new Document("_id", 3).append("x", 4))); collection.bulkWrite(writes); collection.drop(); collection.bulkWrite(writes, new BulkWriteOptions().ordered(false)); // collection.find().forEach(printBlock); // Clean up //database.drop(); // release resources mongoClient.close(); }
From source file:mongoSample.MyMongoDemo.java
License:Apache License
public static void main(final String[] args) { String mongoServer = args[0]; MongoClient mongoClient = new MongoClient(mongoServer); MongoDatabase database = mongoClient.getDatabase("NGDBDemo"); MongoCollection<Document> collection = database.getCollection("test"); collection.drop();/*w w w . jav a 2s .com*/ Document people = new Document(); // A document for a person people.put("Name", "Guy"); people.put("Email", "guy@gmail.com"); BasicDBList friendList = new BasicDBList(); // A list for the persons // friends BasicDBObject friendDoc = new BasicDBObject(); // A document for each // friend friendDoc.put("Name", "Jo"); friendDoc.put("Email", "Jo@gmail.com"); friendList.add(friendDoc); friendDoc.clear(); friendDoc.put("Name", "John"); friendDoc.put("Email", "john@gmail.com"); friendList.add(friendDoc); people.put("Friends", friendDoc); collection.insertOne(people); System.out.println('1'); MongoCursor<Document> cursor = collection.find().iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); } System.out.println('2'); for (Document cur : collection.find()) { System.out.println(cur.toJson()); } System.out.println('3'); // now use a query to get 1 document out Document myDoc = collection.find(eq("Name", "Guy")).first(); System.out.println(myDoc.toJson()); database = mongoClient.getDatabase("sakila"); collection = database.getCollection("films"); for (Document cur : collection.find()) { System.out.println(cur.toJson()); } mongoClient.close(); }
From source file:myapp.MongoDBConnection.java
License:Apache License
public void test() { MongoClient mongoClient = null; try {//from w w w . j a va2 s . com mongoClient = new MongoClient("localhost", 27017); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } //String server = "mongodb://webuser:toniotonio@ds055709.mongolab.com:55709"; //String conectionString = "mongodb://webuser:toniotonio@ds055709.mongolab.com:55709"; // MongoClientURI mongoConecctionURI = new MongoClientURI(conectionString); // MongoClient mongoClient = new MongoClient(mongoConecctionURI); DB db = mongoClient.getDB("primal-manifest"); //boolean auth = db.authenticate("webuser", "toniotonio".toCharArray()); //MongoClient mongoClient = new MongoClient(); // get handle to "mydb" mongoClient.close(); }
From source file:myControls.Main_view.java
private myPanel getGrid() { myPanel pnl = new myPanel(); myTable table = new myTable(); pnl.add(table);/*from ww w . java2s .c o m*/ // MongoClient mongoClient = null; DBCursor cursor = null; mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("kiaan"); DBCollection coll = db.getCollection("banks"); cursor = coll.find(); String[] columnNames = { "id", "name" }; DefaultTableModel model = new DefaultTableModel(columnNames, 0); while (cursor.hasNext()) { DBObject obj = cursor.next(); String first = (String) obj.get("name"); ObjectId id = (ObjectId) obj.get("_id"); model.addRow(new Object[] { id, first }); } table.setModel(model); cursor.close(); mongoClient.close(); // return pnl; }
From source file:net.modelbased.proasense.storage.reader.EventReaderMongoSync.java
License:Apache License
public List<Document> call() { // Connect to MongoDB database MongoClient mongoClient = new MongoClient(new MongoClientURI(this.mongoURL)); MongoDatabase database = mongoClient.getDatabase(this.database); MongoCollection<Document> collection = database.getCollection(this.collectionId); // Create document list for query result List<Document> foundDocuments = new ArrayList<Document>(); if (queryType.equals(EventQueryType.SIMPLE) && queryOperation.equals(EventQueryOperation.DEFAULT)) { FindIterable<Document> it = collection .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime))); MongoCursor<Document> cursor = it.iterator(); while (cursor.hasNext()) { Document doc = cursor.next(); foundDocuments.add(doc);/*from w w w. j a v a 2 s .c o m*/ } } if (queryType.equals(EventQueryType.SIMPLE) && queryOperation.equals(EventQueryOperation.AVERAGE)) { FindIterable<Document> it = collection .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime))); boolean longProperty = false; boolean doubleProperty = false; MongoCursor<Document> firstCursor = it.iterator(); if (firstCursor.hasNext()) { Document doc = firstCursor.next(); Document eventProps = (Document) doc.get("eventProperties"); Object valueObj = eventProps.get(this.propertyKey); if (valueObj instanceof Long) longProperty = true; else if (valueObj instanceof Double) doubleProperty = true; } long resultAverageLong = 0; double resultAverageDouble = 0; long collectionSize = 0; MongoCursor<Document> cursor = it.iterator(); while (cursor.hasNext()) { collectionSize++; Document doc = cursor.next(); Document eventProps = (Document) doc.get("eventProperties"); if (longProperty) { Long value = (Long) eventProps.get(this.propertyKey); resultAverageLong = resultAverageLong + value; } else if (doubleProperty) { Double value = (Double) eventProps.get(this.propertyKey); resultAverageDouble = resultAverageDouble + value; doubleProperty = true; } } if (longProperty) { Long resultAverage = resultAverageLong / collectionSize; Document resultDoc = new Document("RESULT", resultAverage); foundDocuments.add(resultDoc); } else if (doubleProperty) { Double resultAverage = resultAverageDouble / collectionSize; Document resultDoc = new Document("RESULT", resultAverage); foundDocuments.add(resultDoc); } } if (queryType.equals(EventQueryType.SIMPLE) && queryOperation.equals(EventQueryOperation.MAXIMUM)) { FindIterable<Document> it = collection .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime))); boolean longProperty = false; boolean doubleProperty = false; MongoCursor<Document> firstCursor = it.iterator(); if (firstCursor.hasNext()) { Document doc = firstCursor.next(); Document eventProps = (Document) doc.get("eventProperties"); Object valueObj = eventProps.get(this.propertyKey); if (valueObj instanceof Long) longProperty = true; else if (valueObj instanceof Double) doubleProperty = true; } long resultMaximumLong = Long.MIN_VALUE; double resultMaximumDouble = Double.MIN_VALUE; MongoCursor<Document> cursor = it.iterator(); while (cursor.hasNext()) { Document doc = cursor.next(); Document eventProps = (Document) doc.get("eventProperties"); if (longProperty) { long value = (Long) eventProps.get(this.propertyKey); if (value > resultMaximumLong) resultMaximumLong = value; } else if (doubleProperty) { double value = (Double) eventProps.get(this.propertyKey); if (value > resultMaximumDouble) resultMaximumDouble = value; } } if (longProperty) { Long resultMaximum = resultMaximumLong; Document resultDoc = new Document("RESULT", resultMaximum); foundDocuments.add(resultDoc); } else if (doubleProperty) { Double resultMaximum = resultMaximumDouble; Document resultDoc = new Document("RESULT", resultMaximum); foundDocuments.add(resultDoc); } } if (queryType.equals(EventQueryType.SIMPLE) && queryOperation.equals(EventQueryOperation.MINUMUM)) { FindIterable<Document> it = collection .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime))); boolean longProperty = false; boolean doubleProperty = false; MongoCursor<Document> firstCursor = it.iterator(); if (firstCursor.hasNext()) { Document doc = firstCursor.next(); Document eventProps = (Document) doc.get("eventProperties"); Object valueObj = eventProps.get(this.propertyKey); if (valueObj instanceof Long) longProperty = true; else if (valueObj instanceof Double) doubleProperty = true; } long resultMinimumLong = Long.MAX_VALUE; double resultMinimumDouble = Double.MAX_VALUE; MongoCursor<Document> cursor = it.iterator(); while (cursor.hasNext()) { Document doc = cursor.next(); Document eventProps = (Document) doc.get("eventProperties"); if (longProperty) { long value = (Long) eventProps.get(this.propertyKey); if (value < resultMinimumLong) resultMinimumLong = value; } else if (doubleProperty) { Double value = (Double) eventProps.get(this.propertyKey); if (value < resultMinimumDouble) resultMinimumDouble = value; } } if (longProperty) { long resultMinimum = resultMinimumLong; Document resultDoc = new Document("RESULT", resultMinimum); foundDocuments.add(resultDoc); } else if (doubleProperty) { double resultMinimum = resultMinimumDouble; Document resultDoc = new Document("RESULT", resultMinimum); foundDocuments.add(resultDoc); } } if (queryType.equals(EventQueryType.DERIVED) && queryOperation.equals(EventQueryOperation.DEFAULT)) { FindIterable<Document> it = collection .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime))); MongoCursor<Document> cursor = it.iterator(); while (cursor.hasNext()) { Document doc = cursor.next(); foundDocuments.add(doc); } } if (queryType.equals(EventQueryType.DERIVED) && queryOperation.equals(EventQueryOperation.AVERAGE)) { FindIterable<Document> it = collection .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime))); boolean longProperty = false; boolean doubleProperty = false; MongoCursor<Document> firstCursor = it.iterator(); if (firstCursor.hasNext()) { Document doc = firstCursor.next(); Document eventProps = (Document) doc.get("eventProperties"); Object valueObj = eventProps.get(this.propertyKey); if (valueObj instanceof Long) longProperty = true; else if (valueObj instanceof Double) doubleProperty = true; } long resultAverageLong = 0; double resultAverageDouble = 0; long collectionSize = 0; MongoCursor<Document> cursor = it.iterator(); while (cursor.hasNext()) { collectionSize++; Document doc = cursor.next(); Document eventProps = (Document) doc.get("eventProperties"); if (longProperty) { Long value = (Long) eventProps.get(this.propertyKey); resultAverageLong = resultAverageLong + value; } else if (doubleProperty) { Double value = (Double) eventProps.get(this.propertyKey); resultAverageDouble = resultAverageDouble + value; } } if (longProperty) { Long resultAverage = resultAverageLong / collectionSize; Document resultDoc = new Document("RESULT", resultAverage); foundDocuments.add(resultDoc); } else if (doubleProperty) { Double resultAverage = resultAverageDouble / collectionSize; Document resultDoc = new Document("RESULT", resultAverage); foundDocuments.add(resultDoc); } } if (queryType.equals(EventQueryType.DERIVED) && queryOperation.equals(EventQueryOperation.MAXIMUM)) { FindIterable<Document> it = collection .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime))); boolean longProperty = false; boolean doubleProperty = false; MongoCursor<Document> firstCursor = it.iterator(); if (firstCursor.hasNext()) { Document doc = firstCursor.next(); Document eventProps = (Document) doc.get("eventProperties"); Object valueObj = eventProps.get(this.propertyKey); if (valueObj instanceof Long) longProperty = true; else if (valueObj instanceof Double) doubleProperty = true; } long resultMaximumLong = Long.MIN_VALUE; double resultMaximumDouble = Double.MIN_VALUE; MongoCursor<Document> cursor = it.iterator(); while (cursor.hasNext()) { Document doc = cursor.next(); Document eventProps = (Document) doc.get("eventProperties"); if (longProperty) { long value = (Long) eventProps.get(this.propertyKey); if (value > resultMaximumLong) resultMaximumLong = value; } else if (doubleProperty) { double value = (Double) eventProps.get(this.propertyKey); if (value > resultMaximumDouble) resultMaximumDouble = value; doubleProperty = true; } } if (longProperty) { long resultMaximum = resultMaximumLong; Document resultDoc = new Document("RESULT", resultMaximum); foundDocuments.add(resultDoc); } else if (doubleProperty) { double resultMaximum = resultMaximumDouble; Document resultDoc = new Document("RESULT", resultMaximum); foundDocuments.add(resultDoc); } } if (queryType.equals(EventQueryType.DERIVED) && queryOperation.equals(EventQueryOperation.MINUMUM)) { FindIterable<Document> it = collection .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime))); boolean longProperty = false; boolean doubleProperty = false; MongoCursor<Document> firstCursor = it.iterator(); if (firstCursor.hasNext()) { Document doc = firstCursor.next(); Document eventProps = (Document) doc.get("eventProperties"); Object valueObj = eventProps.get(this.propertyKey); if (valueObj instanceof Long) longProperty = true; else if (valueObj instanceof Double) doubleProperty = true; } long resultMinimumLong = Long.MAX_VALUE; double resultMinimumDouble = Double.MAX_VALUE; MongoCursor<Document> cursor = it.iterator(); while (cursor.hasNext()) { Document doc = cursor.next(); Document eventProps = (Document) doc.get("eventProperties"); if (longProperty) { long value = (Long) eventProps.get(this.propertyKey); if (value < resultMinimumLong) resultMinimumLong = value; } else if (doubleProperty) { double value = (Double) eventProps.get(this.propertyKey); if (value < resultMinimumDouble) resultMinimumDouble = value; } } if (longProperty) { long resultMinimum = resultMinimumLong; Document resultDoc = new Document("RESULT", resultMinimum); foundDocuments.add(resultDoc); } else if (doubleProperty) { double resultMinimum = resultMinimumDouble; Document resultDoc = new Document("RESULT", resultMinimum); foundDocuments.add(resultDoc); } } if (queryType.equals(EventQueryType.PREDICTED) && queryOperation.equals(EventQueryOperation.DEFAULT)) { FindIterable<Document> it = collection .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime))); MongoCursor<Document> cursor = it.iterator(); while (cursor.hasNext()) { Document doc = cursor.next(); foundDocuments.add(doc); } } if (queryType.equals(EventQueryType.PREDICTED) && queryOperation.equals(EventQueryOperation.AVERAGE)) { FindIterable<Document> it = collection .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime))); boolean longProperty = false; boolean doubleProperty = false; MongoCursor<Document> firstCursor = it.iterator(); if (firstCursor.hasNext()) { Document doc = firstCursor.next(); Document eventProps = (Document) doc.get("eventProperties"); Object valueObj = eventProps.get(this.propertyKey); if (valueObj instanceof Long) longProperty = true; else if (valueObj instanceof Double) doubleProperty = true; } long resultAverageLong = 0; double resultAverageDouble = 0; long collectionSize = 0; MongoCursor<Document> cursor = it.iterator(); while (cursor.hasNext()) { collectionSize++; Document doc = cursor.next(); Document eventProps = (Document) doc.get("eventProperties"); if (longProperty) { long value = (Long) eventProps.get(this.propertyKey); resultAverageLong = resultAverageLong + value; } else if (doubleProperty) { double value = (Double) eventProps.get(this.propertyKey); resultAverageDouble = resultAverageDouble + value; } } if (longProperty) { long resultAverage = resultAverageLong / collectionSize; Document resultDoc = new Document("RESULT", resultAverage); foundDocuments.add(resultDoc); } else if (doubleProperty) { double resultAverage = resultAverageDouble / collectionSize; Document resultDoc = new Document("RESULT", resultAverage); foundDocuments.add(resultDoc); } } if (queryType.equals(EventQueryType.PREDICTED) && queryOperation.equals(EventQueryOperation.MAXIMUM)) { FindIterable<Document> it = collection .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime))); boolean longProperty = false; boolean doubleProperty = false; MongoCursor<Document> firstCursor = it.iterator(); if (firstCursor.hasNext()) { Document doc = firstCursor.next(); Document eventProps = (Document) doc.get("eventProperties"); Object valueObj = eventProps.get(this.propertyKey); if (valueObj instanceof Long) longProperty = true; else if (valueObj instanceof Double) doubleProperty = true; } long resultMaximumLong = Long.MIN_VALUE; double resultMaximumDouble = Double.MIN_VALUE; MongoCursor<Document> cursor = it.iterator(); while (cursor.hasNext()) { Document doc = cursor.next(); Document eventProps = (Document) doc.get("eventProperties"); if (longProperty) { long value = (Long) eventProps.get(this.propertyKey); if (value > resultMaximumLong) resultMaximumLong = value; } else if (doubleProperty) { double value = (Double) eventProps.get(this.propertyKey); if (value > resultMaximumDouble) resultMaximumDouble = value; } } if (longProperty) { long resultMaximum = resultMaximumLong; Document resultDoc = new Document("RESULT", resultMaximum); foundDocuments.add(resultDoc); } else if (doubleProperty) { double resultMaximum = resultMaximumDouble; Document resultDoc = new Document("RESULT", resultMaximum); foundDocuments.add(resultDoc); } } if (queryType.equals(EventQueryType.PREDICTED) && queryOperation.equals(EventQueryOperation.MINUMUM)) { FindIterable<Document> it = collection .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime))); boolean longProperty = false; boolean doubleProperty = false; MongoCursor<Document> firstCursor = it.iterator(); if (firstCursor.hasNext()) { Document doc = firstCursor.next(); Document eventProps = (Document) doc.get("eventProperties"); Object valueObj = eventProps.get(this.propertyKey); if (valueObj instanceof Long) longProperty = true; else if (valueObj instanceof Double) doubleProperty = true; } long resultMinimumLong = Long.MAX_VALUE; double resultMinimumDouble = Double.MAX_VALUE; MongoCursor<Document> cursor = it.iterator(); while (cursor.hasNext()) { Document doc = cursor.next(); Document eventProps = (Document) doc.get("eventProperties"); if (longProperty) { long value = (Long) eventProps.get(this.propertyKey); if (value < resultMinimumLong) resultMinimumLong = value; } else if (doubleProperty) { double value = (Long) eventProps.get(this.propertyKey); if (value < resultMinimumDouble) resultMinimumDouble = value; } } if (longProperty) { long resultMinimum = resultMinimumLong; Document resultDoc = new Document("RESULT", resultMinimum); foundDocuments.add(resultDoc); } else if (doubleProperty) { double resultMinimum = resultMinimumDouble; Document resultDoc = new Document("RESULT", resultMinimum); foundDocuments.add(resultDoc); } } if (queryType.equals(EventQueryType.ANOMALY) && queryOperation.equals(EventQueryOperation.DEFAULT)) { FindIterable<Document> it = collection .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime))); MongoCursor<Document> cursor = it.iterator(); while (cursor.hasNext()) { Document doc = cursor.next(); foundDocuments.add(doc); } } if (queryType.equals(EventQueryType.RECOMMENDATION) && queryOperation.equals(EventQueryOperation.DEFAULT)) { FindIterable<Document> it = collection .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime))); MongoCursor<Document> cursor = it.iterator(); while (cursor.hasNext()) { Document doc = cursor.next(); foundDocuments.add(doc); } } if (queryType.equals(EventQueryType.RECOMMENDATION) && queryOperation.equals(EventQueryOperation.AVERAGE)) { FindIterable<Document> it = collection .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime))); boolean longProperty = false; boolean doubleProperty = false; MongoCursor<Document> firstCursor = it.iterator(); if (firstCursor.hasNext()) { Document doc = firstCursor.next(); Document eventProps = (Document) doc.get("eventProperties"); Object valueObj = eventProps.get(this.propertyKey); if (valueObj instanceof Long) longProperty = true; else if (valueObj instanceof Double) doubleProperty = true; } long resultAverageLong = 0; double resultAverageDouble = 0; long collectionSize = 0; MongoCursor<Document> cursor = it.iterator(); while (cursor.hasNext()) { collectionSize++; Document doc = cursor.next(); Document eventProps = (Document) doc.get("eventProperties"); if (longProperty) { long value = (Long) eventProps.get(this.propertyKey); resultAverageLong = resultAverageLong + value; } else if (doubleProperty) { double value = (Double) eventProps.get(this.propertyKey); resultAverageDouble = resultAverageDouble + value; } } if (longProperty) { long resultAverage = resultAverageLong / collectionSize; Document resultDoc = new Document("RESULT", resultAverage); foundDocuments.add(resultDoc); } else if (doubleProperty) { double resultAverage = resultAverageDouble / collectionSize; Document resultDoc = new Document("RESULT", resultAverage); foundDocuments.add(resultDoc); } } if (queryType.equals(EventQueryType.RECOMMENDATION) && queryOperation.equals(EventQueryOperation.MAXIMUM)) { FindIterable<Document> it = collection .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime))); boolean longProperty = false; boolean doubleProperty = false; MongoCursor<Document> firstCursor = it.iterator(); if (firstCursor.hasNext()) { Document doc = firstCursor.next(); Document eventProps = (Document) doc.get("eventProperties"); Object valueObj = eventProps.get(this.propertyKey); if (valueObj instanceof Long) longProperty = true; else if (valueObj instanceof Double) doubleProperty = true; } long resultMaximumLong = Long.MIN_VALUE; double resultMaximumDouble = Double.MIN_VALUE; MongoCursor<Document> cursor = it.iterator(); while (cursor.hasNext()) { Document doc = cursor.next(); Document eventProps = (Document) doc.get("eventProperties"); if (longProperty) { long value = (Long) eventProps.get(this.propertyKey); if (value > resultMaximumLong) resultMaximumLong = value; } else if (doubleProperty) { double value = (Double) eventProps.get(this.propertyKey); if (value > resultMaximumDouble) resultMaximumDouble = value; } } if (longProperty) { long resultMaximum = resultMaximumLong; Document resultDoc = new Document("RESULT", resultMaximum); foundDocuments.add(resultDoc); } else if (doubleProperty) { double resultMaximum = resultMaximumDouble; Document resultDoc = new Document("RESULT", resultMaximum); foundDocuments.add(resultDoc); } } if (queryType.equals(EventQueryType.RECOMMENDATION) && queryOperation.equals(EventQueryOperation.MINUMUM)) { FindIterable<Document> it = collection .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime))); boolean longProperty = false; boolean doubleProperty = false; MongoCursor<Document> firstCursor = it.iterator(); if (firstCursor.hasNext()) { Document doc = firstCursor.next(); Document eventProps = (Document) doc.get("eventProperties"); Object valueObj = eventProps.get(this.propertyKey); if (valueObj instanceof Long) longProperty = true; else if (valueObj instanceof Double) doubleProperty = true; } long resultMinimumLong = Long.MAX_VALUE; double resultMinimumDouble = Double.MAX_VALUE; MongoCursor<Document> cursor = it.iterator(); while (cursor.hasNext()) { Document doc = cursor.next(); Document eventProps = (Document) doc.get("eventProperties"); if (longProperty) { long value = (Long) eventProps.get(this.propertyKey); if (value < resultMinimumLong) resultMinimumLong = value; } else if (doubleProperty) { double value = (Double) eventProps.get(this.propertyKey); if (value < resultMinimumDouble) resultMinimumDouble = value; } } if (longProperty) { long resultMinimum = resultMinimumLong; Document resultDoc = new Document("RESULT", resultMinimum); foundDocuments.add(resultDoc); } else if (doubleProperty) { double resultMinimum = resultMinimumDouble; Document resultDoc = new Document("RESULT", resultMinimum); foundDocuments.add(resultDoc); } } if (queryType.equals(EventQueryType.FEEDBACK) && queryOperation.equals(EventQueryOperation.DEFAULT)) { FindIterable<Document> it = collection .find(and(gte("timestamp", this.startTime), lte("timestamp", this.endTime))); MongoCursor<Document> cursor = it.iterator(); while (cursor.hasNext()) { Document doc = cursor.next(); foundDocuments.add(doc); } } mongoClient.close(); return foundDocuments; }
From source file:net.modelbased.proasense.storage.writer.EventWriterMongoSync.java
License:Apache License
public void run() { // Connect to MongoDB database MongoClient mongoClient = new MongoClient(new MongoClientURI(mongoURL)); MongoDatabase database = mongoClient.getDatabase(EventProperties.STORAGE_DATABASE_NAME); // Create hash map of collections Map<String, MongoCollection<Document>> collectionMap = new HashMap<String, MongoCollection<Document>>(); int cnt = 0;//from w ww. j a v a2s . c om long timer0 = System.currentTimeMillis(); long timer1 = timer0; long timer2 = timer0; boolean skipLog = false; Map<String, List<Document>> documentMap = new HashMap<String, List<Document>>(); try { if (isLogfile) logfileWriter = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("EventWriterMongoSync_benchmark_" + this.threadNumber + ".txt"), "ISO-8859-1")); while (true) { long timeoutExpired = System.currentTimeMillis() + this.maxWait; EventDocument eventDocument = queue.take(); String collectionId = eventDocument.getCollectionId(); if (!collectionId.matches(EventProperties.STORAGE_HEARTBEAT)) { cnt++; skipLog = false; } else skipLog = true; // Add data for bulk write if (!collectionId.matches(EventProperties.STORAGE_HEARTBEAT)) { Document document = eventDocument.getDocument(); if (!collectionMap.containsKey(collectionId)) { collectionMap.put(collectionId, database.getCollection(collectionId)); List<Document> documentList = new ArrayList<Document>(); documentMap.put(collectionId, documentList); } documentMap.get(collectionId).add(document); } // Write data if heartbeat timeout is received else { for (Map.Entry<String, MongoCollection<Document>> entry : collectionMap.entrySet()) { String key = entry.getKey(); if (!documentMap.get(key).isEmpty()) { collectionMap.get(key).insertMany(documentMap.get(key)); documentMap.get(key).clear(); } } } // Write data if bulk size or max wait (ms) is reached if ((cnt % this.bulkSize == 0) || (System.currentTimeMillis() >= timeoutExpired)) { for (Map.Entry<String, MongoCollection<Document>> entry : collectionMap.entrySet()) { String key = entry.getKey(); if (!documentMap.get(key).isEmpty()) { collectionMap.get(key).insertMany(documentMap.get(key)); documentMap.get(key).clear(); } } } // Benchmark output if ((!skipLog) && (cnt % this.logSize == 0)) { timer2 = System.currentTimeMillis(); long difference = timer2 - timer1; if (difference != 0) { long average = (this.logSize * 1000) / (timer2 - timer1); System.out.println("Benchmark: "); System.out.println(" Records written : " + cnt); System.out.println(" Average records/s: " + average); timer1 = timer2; if (isLogfile) { logfileWriter.write(cnt + "," + average + System.getProperty("line.separator")); logfileWriter.flush(); } if (cnt == this.loadTestMaxMessages) { long loadTestStart = timer0 / 1000; long loadTestEnd = timer2 / 1000; long loadTestTime = loadTestEnd - loadTestStart; long loadTestAverage = this.loadTestMaxMessages / loadTestTime; System.out.println("*****************************"); System.out.println("Load test results: "); System.out.println(" Records written : " + cnt); System.out.println(" Average records/s: " + loadTestAverage); if (isLogfile) { logfileWriter.write( "*****************************" + System.getProperty("line.separator")); logfileWriter.write("Load test results: " + System.getProperty("line.separator")); logfileWriter.write( " Records written : " + cnt + System.getProperty("line.separator")); logfileWriter.write(" Average records/s: " + loadTestAverage + System.getProperty("line.separator")); logfileWriter.flush(); } } } } } } catch (InterruptedException e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } catch (IOException e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } finally { if (isLogfile) try { logfileWriter.close(); } catch (IOException e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } } mongoClient.close(); }
From source file:net.ymate.platform.persistence.mongodb.MongoDB.java
License:Apache License
/** * ?MongoDB?//w ww. ja v a2 s . c o m */ public static void destroy() { if (isInited) { for (MongoClient _client : __DATASOURCE_CACHE.values()) { _client.close(); } __DATASOURCE_CACHE.clear(); __DATASOURCE_CFG_METAS.clear(); __REPOSTORY_BEAN_FACTORY = null; isInited = false; } }
From source file:nl.mvdb.mongodb.RemoveStudentsLowestHomeworkScore.java
License:Apache License
public static void main(String[] args) { MongoClient client = new MongoClient(); try {//w w w . j a v a2 s . c o m MongoDatabase database = client.getDatabase("school"); MongoCollection<Document> collection = database.getCollection("students"); MongoCursor<Document> iterator = collection.find().sort(ascending("scores.score")).iterator(); while (iterator.hasNext()) { Document studentDoc = iterator.next(); System.out.println(studentDoc); Document lowestScoreDoc = null; List<Document> scoreDocs = (ArrayList) studentDoc.get("scores"); for (Document scoreDoc : scoreDocs) { if ("homework".equals(scoreDoc.getString("type"))) { Double score = scoreDoc.getDouble("score"); if (lowestScoreDoc == null || score < lowestScoreDoc.getDouble("score")) { lowestScoreDoc = scoreDoc; } } } if (lowestScoreDoc != null) { scoreDocs.remove(lowestScoreDoc); studentDoc.put("scores", scoreDocs); collection.replaceOne(new Document("_id", studentDoc.getInteger("_id")), studentDoc); } } System.out.println(collection.count()); } finally { client.close(); } }
From source file:nl.mvdb.mongodb.RemoveStudentsLowestScore.java
License:Apache License
public static void main(String[] args) { MongoClient client = new MongoClient(); try {/*from w ww. j av a 2 s . co m*/ MongoDatabase database = client.getDatabase("students"); MongoCollection<Document> collection = database.getCollection("grades"); MongoCursor<Document> iterator = collection.find().sort(ascending("student_id", "score")).iterator(); Integer lastStudentId = null; while (iterator.hasNext()) { Document gradingDoc = iterator.next(); Integer studentId = gradingDoc.getInteger("student_id"); if (!studentId.equals(lastStudentId)) { lastStudentId = studentId; System.out.println(lastStudentId); collection.deleteOne(gradingDoc); } } System.out.println(collection.count()); } finally { client.close(); } }