List of usage examples for com.mongodb.client MongoDatabase getCollection
MongoCollection<Document> getCollection(String collectionName);
From source file:com.mycompany.database.MongodbDataBaseClass.java
public void dududu() { System.out.println("not error"); MongoClient mongoClient = new MongoClient("localhost", 27017); MongoDatabase database = mongoClient.getDatabase("testdb"); System.out.println("not error"); MongoCollection<Document> col = database.getCollection("cars"); try (MongoCursor<Document> cur = col.find().iterator()) { while (cur.hasNext()) { Document doc = cur.next(); List list = new ArrayList(doc.values()); System.out.print(list.get(1)); System.out.print(": "); System.out.println(list.get(2)); }// w w w. j a v a 2 s .c o m } mongoClient.close(); }
From source file:com.mysweethome.TemperaturePersisterTimerTask.java
public synchronized void persistDataOnMongolab() { //disable console logging //Logger mongoLogger = Logger.getLogger("org.mongodb.driver"); //mongoLogger.setLevel(Level.SEVERE); iStoredTemperatures = iTemperatureStore.getTemperatures(); if (iStoredTemperatures.isEmpty()) { logger.info("Nothing to persist. Exiting"); return;// w w w.j a va 2s.c o m } logger.info("Prepairing to persist [{}] Temps in the cloud", iStoredTemperatures.size()); MongoCollection<Document> mongoCollection = null; MongoClient client = null; List<Document> documents = new ArrayList<Document>(); for (TemperatureMeasure tTemp : iStoredTemperatures) { //Exception in thread "Timer-2" java.util.ConcurrentModificationException Document doc = new Document(); doc.put("Location", tTemp.getLocation()); //Location doc.put("Group", tTemp.getGroup()); //Group doc.put("Date", Helper.getDateAsString(tTemp.getDate())); //Date doc.put("Day", Helper.getDayAsString(tTemp.getDate())); doc.put("Time", Helper.getTimeAsString(tTemp.getDate())); doc.put("Temp", Helper.getTempAsString(tTemp.getTemp())); //Temp documents.add(doc); iPersistedTemperatures.add(tTemp); } try { MongoClientURI uri = new MongoClientURI(MySweetHomeProperties.ML_URL); client = new MongoClient(uri); MongoDatabase database = (MongoDatabase) client.getDatabase(uri.getDatabase()); mongoCollection = database.getCollection("dailytemps"); mongoCollection.insertMany(documents); //eliminate stored Temps from the collection iTemperatureStore.removeAll(iPersistedTemperatures); client.close(); logger.info("Temperatures persisted on mongolab: [{}]. Exiting.", iPersistedTemperatures.size()); iPersistedTemperatures.clear(); } catch (Throwable e) { logger.error("Failed to store Temps in the cloud. Stacktrace: [{}]. Exiting.", e); iPersistedTemperatures.clear(); e.printStackTrace(); } finally { if (client != null) { client.close(); } iPersistedTemperatures.clear(); } }
From source file:com.netflix.config.sources.MongoDBConfigurationSource.java
License:Apache License
/** * Returns a <code>Map<String, Object></code> of properties stored in the * database./*from w w w. j a va 2 s .c o m*/ * * @throws Exception */ synchronized Map<String, Object> load() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); try { final MongoDatabase database = mongoClient.getDatabase(databaseName); final MongoCollection<Document> collection = database.getCollection(collectionName); final FindIterable<Document> documents = collection.find(); for (Document document : documents) { final Object id = document.get("_id"); if (id != null && document.containsKey("value")) { final Object value = document.get("value"); map.put(id.toString(), value); } } } catch (Exception e) { log.error("Failed to load archaius settings from MongoDB.", e); throw e; } return map; }
From source file:com.px100systems.data.plugin.storage.mongo.MongoDatabaseStorage.java
License:Open Source License
public Map<String, List<String>> getSchema(boolean reset) { MongoDatabase db = mongoClient.getDatabase(databaseName); Map<String, List<String>> result = new HashMap<>(); MongoCursor<String> cursor = db.listCollectionNames().iterator(); try {/*from www.ja v a2 s . c o m*/ while (cursor.hasNext()) { String name = cursor.next(); if (!name.startsWith("system.")) if (reset) db.getCollection(name).drop(); else result.put(name, new ArrayList<String>()); } } finally { cursor.close(); } for (Map.Entry<String, List<String>> e : result.entrySet()) { MongoCursor<Document> idxCursor = db.getCollection(e.getKey()).listIndexes().iterator(); try { while (idxCursor.hasNext()) { Document idx = idxCursor.next(); String indexName = idx.get("name", String.class); if (CompoundIndexDescriptor.isCompondIndexName(indexName)) e.getValue().add(indexName); else { String name = idx.get("key", Document.class).keySet().iterator().next(); if (!name.startsWith("_")) e.getValue().add(name); } } } finally { idxCursor.close(); } } return result; }
From source file:com.px100systems.data.plugin.storage.mongo.MongoDatabaseStorage.java
License:Open Source License
public void createEntity(String unitName, Collection<String> indexedFields, List<CompoundIndexDescriptor> compoundIndexes) { MongoDatabase db = mongoClient.getDatabase(databaseName); db.createCollection(unitName);/*from w ww . j a v a2s . c om*/ List<IndexModel> indexes = new ArrayList<>(); for (CompoundIndexDescriptor ci : compoundIndexes) { Map<String, Object> fields = new HashMap<>(); for (CompoundIndexDescriptor.Field field : ci.getFields()) fields.put(field.getName(), field.isDescending() ? "-1" : "1"); indexes.add(new IndexModel(new Document(fields), new IndexOptions().name(indexName(ci.getName())).background(true))); } for (String idx : indexedFields) indexes.add( new IndexModel(new Document(idx, 1), new IndexOptions().name(indexName(idx)).background(true))); db.getCollection(unitName).createIndexes(indexes); }
From source file:com.px100systems.data.plugin.storage.mongo.MongoDatabaseStorage.java
License:Open Source License
public void dropEntity(String unitName) { if (unitName.startsWith("system.")) // just a precation, shouldn't happen return;/*from w w w . j ava 2 s. co m*/ MongoDatabase db = mongoClient.getDatabase(databaseName); try { db.getCollection(unitName).drop(); } catch (MongoCommandException ignored) { } }
From source file:com.px100systems.data.plugin.storage.mongo.MongoDatabaseStorage.java
License:Open Source License
public void addIndexes(String unitName, List<String> newIndexes, List<CompoundIndexDescriptor> newCompoundIndexes) { MongoDatabase db = mongoClient.getDatabase(databaseName); List<IndexModel> indexes = new ArrayList<>(); for (CompoundIndexDescriptor ci : newCompoundIndexes) { Map<String, Object> fields = new HashMap<>(); for (CompoundIndexDescriptor.Field field : ci.getFields()) fields.put(field.getName(), field.isDescending() ? "-1" : "1"); indexes.add(new IndexModel(new Document(fields), new IndexOptions().name(indexName(ci.getName())).background(true))); }// w w w . java 2s. co m for (String idx : newIndexes) indexes.add( new IndexModel(new Document(idx, 1), new IndexOptions().name(indexName(idx)).background(true))); db.getCollection(unitName).createIndexes(indexes); }
From source file:com.px100systems.data.plugin.storage.mongo.MongoDatabaseStorage.java
License:Open Source License
public void dropIndex(String unitName, String obsoleteIndex) { if (obsoleteIndex.startsWith("_")) // just a precation, shouldn't happen return;/*from ww w. j a va2s . c o m*/ MongoDatabase db = mongoClient.getDatabase(databaseName); try { db.getCollection(unitName).dropIndex(indexName(obsoleteIndex)); } catch (MongoCommandException ignored) { } }
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
@SuppressWarnings("unchecked") public <T> T get(String unitName, Class<T> cls, Long id) { MongoDatabase db = mongoClient.getDatabase(databaseName); Document doc = db.getCollection(unitName).find(Filters.eq("id", id)).limit(1).first(); if (doc == null) return null; SerializationDefinition def = SerializationDefinition.get(cls); if (def == null) throw new RuntimeException("Cannot find SerializedDefinition for " + cls.getSimpleName()); T result = (T) def.newInstance();/*w ww . jav a2 s.c om*/ def.read(doc, result); return result; }