List of usage examples for com.mongodb.client MongoDatabase getCollection
MongoCollection<Document> getCollection(String collectionName);
From source file:consultasEntradaSaidaArquivo.LeituraXLS.java
public static void lerArquivo(MongoDatabase db, String fileName) throws IOException, BiffException { //System.out.println("Entramo na funcao"); String filePath = "src/arquivosPlataformaP56/" + fileName; WorkbookSettings ws = new WorkbookSettings();// resolver o problema de encoding. ws.setEncoding("Cp1252");//enconding com utf-8 Workbook workbook = Workbook.getWorkbook(new File(filePath), ws); Sheet sheet = workbook.getSheet(0);/*from www . j a v a 2 s . com*/ for (int linha = 1; linha < sheet.getRows(); linha++) { Document doc = new Document(); //Mudei para o Tipo Document, pq o mongo pede esse tipo ao invez do json, ele faz a convercao dele de document para json for (int coluna = 0; coluna < sheet.getColumns(); coluna++) { Cell cell = sheet.getCell(coluna, linha); //if( !cell.getContents().isEmpty() ) { if ((!cell.getContents().isEmpty()) && (!sheet.getCell(0, linha).getContents().isEmpty())) { String fullName = fileName; String[] noDot = fullName.split("\\."); String[] noUnderline = noDot[0].split("_"); String modulo = noUnderline[1]; String setor = noUnderline[2]; doc.append("#grupo", noDot[0]); doc.append("modulo", modulo); doc.append("setor", setor); if (sheet.getCell(coluna, 0).getContents().equals("&?rea (m2)")) { //precisamos converter de string para numeric para o mongo poder calcular double value; if (cell.getType() != CellType.NUMBER) { String tempCell = "" + cell.getContents(); tempCell = tempCell.replace(",", "."); value = Double.parseDouble(tempCell); } else { NumberCell nc = (NumberCell) cell; value = nc.getValue(); } doc.append("area", value); } else if (coluna == 2) { String cellZone = cell.getContents(); // Padronizando a coluna de zonas, e tratando de typos (Zona Alta X; Zona X Alta; Zona alta X; Zona altaX; Zona baixa X; Zona L Alta ;) if (cellZone.matches("(\\w+) (Alta) (\\w+)")) { cellZone = cellZone.replaceAll("(\\w+) (Alta) (\\w+)", "$1 $3 $2"); } else if (cellZone.matches("(\\w+) (alta) (\\w+)")) { cellZone = cellZone.replaceAll("(\\w+) (alta) (\\w+)", "$1 $3 Alta"); } else if (cellZone.matches("(\\w+) (baixa)(\\s+)(\\w+)")) { cellZone = cellZone.replaceAll("(\\w+) (baixa) (\\w+)", "$1 $3"); } else if (cellZone.matches("(\\w+) (alta)(\\w+)")) { cellZone = cellZone.replaceAll("(\\w+) (alta)(\\w+)", "$1 $3 Alta"); } else if (cellZone.matches("(Zona) (\\w+) (Alta)(\\s+)")) { cellZone = cellZone.replaceAll("(Zona) (\\w+) (Alta)(\\s+)", "$1 $2 $3"); } doc.append("subgrupo-zona", cellZone); } else { doc.append(sheet.getCell(coluna, 0).getContents(), cell.getContents()); } } } db.getCollection("pt").insertOne(doc);//salvar os documentos na collection pt. } workbook.close(); //comandos importantes: // Deletar toda a collection db.pt.remove({}) // db.pt.findOne({"#nome":"FLG-04A 420"}) // it // db.pt.count({ "#subgrupo" : "zona A"}) // db.pt.count({"supgrupo-zona":/.*Alta.*/}) // db.pt.find().limit(-1).skip(x).next() // pegar registro aleatrio // Item 1): db.pt.aggregate([ {$match:{"#nome":/.*/} }, {$match:{"subgrupo-zona":/.*Alta.*/} }, {$group:{_id:"$subgrupo-zona",total:{$sum:"$area"}}}, {$sort: { total: -1 }} ]) // Item 2): ( db.pt.stats() * 100 / db.pt.count({"supgrupo-zona":/.*Alta.*/}) ) // db.pt.count({"subgrupo-zona":"Zona C Alta","#nome":/.*/}) // Item 3): db.pt.find({"#nome":/.*/,"*NPD":/.*/},{"*NPD":1,"_id":0,"#nome":1}).pretty() // modulo & setor // db.pt.aggregate([ {$group:{_id:{"modulo":"$modulo","setor":"$setor"},total:{$sum:"$area"}}}, {$sort: { modulo: -1 }} ]) }
From source file:consultasMongoDB.MongoConsultas.java
public static MongoCollection<Document> initiateMongoCollection() { MongoClient mongoClient = new MongoClient(); MongoDatabase database = mongoClient.getDatabase("plataforma"); MongoCollection<Document> ptCollection = database.getCollection("pt"); return ptCollection; }
From source file:course.homework.Homework2_3.java
License:Apache License
public static void main(String[] args) { MongoClient client = new MongoClient(); MongoDatabase database = client.getDatabase("students"); final MongoCollection<Document> collection = database.getCollection("grades"); Bson filter = Filters.eq("type", "homework"); Bson sort = Sorts.descending("student_id", "score"); Set<Object> keys = new HashSet<>(); collection.find(filter).sort(sort).into(new ArrayList<Document>()).stream().forEach(doc -> { if (keys.contains(doc.get("student_id"))) { System.out.println("Already exists " + doc.get("student_id") + " = " + doc.get("score")); collection.deleteOne(Filters.eq("_id", doc.getObjectId("_id"))); } else {/*from w ww. j ava2s . co m*/ System.out.println("Does not exist " + doc.get("student_id") + " = " + doc.get("score")); keys.add(doc.get("student_id")); } }); }
From source file:course.homework.Homework3.java
License:Apache License
public static void main(String[] args) { MongoClient client = new MongoClient(); MongoDatabase database = client.getDatabase("school"); MongoCollection<Document> collection = database.getCollection("students"); MongoCursor<Document> iterator = collection.find().iterator(); while (iterator.hasNext()) { Document doc = iterator.next(); List<Document> scores = (List<Document>) doc.get("scores"); Optional<Document> bestHomeWork = scores.stream() .max((a, b) -> a.getString("type").equals("homework") && b.getString("type").equals("homework") ? Double.compare(a.getDouble("score"), b.getDouble("score")) : -1);/* www . ja v a 2 s. c om*/ Double bestScore = bestHomeWork.get().getDouble("score"); List<Document> result = scores.stream() .filter(x -> !x.getString("type").equals("homework") || x.getDouble("score").equals(bestScore)) .collect(Collectors.toList()); collection.updateOne(eq("_id", doc.get("_id")), new Document("$set", new Document("scores", result))); } iterator.close(); client.close(); }
From source file:course.homework.week2.RemoveLowest.java
License:Apache License
public static void main(final String[] args) { MongoClient client = new MongoClient(); MongoDatabase numbersDB = client.getDatabase("students"); MongoCollection<Document> grades = numbersDB.getCollection("grades"); MongoCursor<Document> cursor = grades.find(eq("type", "homework")).sort(ascending("student_id", "score")) .iterator();//from w w w.ja v a 2s . c o m Object studentId = -1; try { while (cursor.hasNext()) { Document entry = cursor.next(); if (!entry.get("student_id").equals(studentId)) { System.out.println("Removing: " + entry); Object id = entry.get("_id"); grades.deleteOne(eq("_id", id)); } studentId = entry.get("student_id"); } } finally { cursor.close(); } }
From source file:course.NewsPostDAO.java
License:Apache License
public NewsPostDAO(final MongoDatabase newsDatabase) { postsCollection = newsDatabase.getCollection("posts"); }
From source file:course.StatsDAO.java
License:Apache License
public StatsDAO(final MongoDatabase blogDatabase) { statsCollection = blogDatabase.getCollection("Stats"); }
From source file:Dao.AccessDataNOSQL.java
License:Open Source License
/** * Metodo que se conecta a una coleccion de una base de datos no sql * @param baseDatos la base de datos a la que se conecta * @param coleccion coleccion de la base de datos * @return devuelve la coleccion de la base de datos a la que se conecta */// w w w . ja v a 2 s. c om public MongoCollection<Document> consultaBD(String baseDatos, String coleccion) { String direccion = "mongodb://" + getUser() + ":" + getPassword() + "@" + getCadenaConexion(); //mongodb://bogdan:ar03pbo@ds033337.mongolab.com:33337/nosql MongoClientURI connectionString = new MongoClientURI(direccion); MongoClient mongoClient = new MongoClient(connectionString); MongoDatabase database = mongoClient.getDatabase(baseDatos);//nosql MongoCollection<Document> collec = database.getCollection(coleccion); return collec; }
From source file:dao.DaoDocumentos.java
public boolean salvarCompra(Compra compra) { MongoClient client = new MongoClient("localhost", 27017); MongoDatabase dataBase = client.getDatabase("bdnc-loja"); MongoCollection<Document> collection = dataBase.getCollection("vendas"); collection.insertOne(compra.toDocument()); client.close();// www .j av a 2 s. c o m return true; }
From source file:dao.DaoDocumentos.java
public List<Compra> buscarCompras() { MongoClient client = new MongoClient("localhost", 27017); MongoDatabase dataBase = client.getDatabase("bdnc-loja"); 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.convertFromDocument(cursor.next())); }// w w w .jav a 2s. c om client.close(); return compras; }