List of usage examples for com.mongodb MongoClient getDB
@Deprecated public DB getDB(final String dbName)
From source file:javaapplication1.InsertUser.java
public static void main(String[] args) { MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("PaperTree"); DBCollection user = db.getCollection("User"); Document d = new Document(); d.put("Name", new Document().append("First Name", "Akshay").append("Last Name", "Chandila")); d.put("Email", "akki@gmail.com"); d.put("Interests", "Computer Science"); d.put("Password", "shaolinp"); d.put("Security Question", "a?"); d.put("Security Answer", "b"); DBObject ob = new BasicDBObject(d); user.insert(ob);//from w ww . jav a 2 s .c o m DBObject ob1 = new BasicDBObject(new Document("Password", "shaolinp")); DBObject ob2 = new BasicDBObject(new Document("$set", new Document("Security Answer", "Akshay1234"))); user.update(ob1, ob2); String tm = "shaolghjmkl;inp"; DBObject ob3 = new BasicDBObject(new Document("Password", tm)); DBCursor c2 = user.find(ob3); System.out.println(c2.count()); }
From source file:javaapplication15.JavaApplication15.java
/** * @param args the command line arguments * @throws java.net.UnknownHostException *//*from w ww . j a v a 2 s . co m*/ public static void main(String[] args) throws UnknownHostException { MongoClient client = new MongoClient("localhost", 27017); DB myDB = client.getDB("m101"); DBCollection collection = myDB.getCollection("Sample2"); collection.drop(); BasicDBObject query = new BasicDBObject("x", new BasicDBObject("$gt", 10).append("$lt", 50)).append("y", new BasicDBObject("$gt", 10).append("$lt", 50)); for (int i = 0; i < 10; i++) { collection.insert( new BasicDBObject("x", new Random().nextInt(100)).append("y", new Random().nextInt(100))); } // DBObject one = collection.findOne(query); // System.out.println(one); DBCursor cursor = collection.find(query); try { while (cursor.hasNext()) { DBObject dBObject = cursor.next(); System.out.println(dBObject); } } finally { cursor.close(); } }
From source file:javaapplication3.JavaApplication3.java
public static void main(String args[]) { try {// w w w .ja va 2 s . co m // To connect to mongodb server MongoClient mongoClient = new MongoClient("localhost", 27017); // Now connect to your databases DB db = mongoClient.getDB("test"); System.out.println("Connect to database successfully"); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } }
From source file:javamongo.JavaMongo.java
public static void main(String[] args) { try {// ww w . j ava 2 s .c om MongoClient client = new MongoClient(); DB banco = client.getDB("javadb");//cria ou acessa uma instncia DB mongo DBCollection colecao = banco.getCollection("pessoas"); //Salvar /* BasicDBObject p1 = new BasicDBObject(); p1.append("Nome", "Joao"); p1.append("Idade", 20); colecao.save(p1); p1.append("Nome", "Maria"); p1.append("Idade", 20); BasicDBObject endereco = new BasicDBObject(); endereco.append("Logradouro", "Avemida Brasil"); endereco.append("Numero", 1090); endereco.append("Complemento", "Ap 200"); p1.append("Endereco", endereco); ArrayList<String> telefones = new ArrayList<>(); telefones.add("047 33216598"); telefones.add("047 99699999"); p1.append("Telefones", telefones); colecao.save(p1); */ //consulta /* //where BasicDBObject where = new BasicDBObject("Nome","Aninha"); //where nome = aninha BasicDBObject where = new BasicDBObject("Idade", new BasicDBObject("$gte",5)); //where idade >= 5 //select DBCursor cursor = colecao.find(); //select tudo DBCursor cursor = colecao.find(where); while (cursor.hasNext()) { BasicDBObject documento = (BasicDBObject)cursor.next(); System.out.println("Nome: "+documento.getString("Nome")); System.out.println("Endereco: "+documento.getString("Endereco")); System.out.println("Complemento: "+documento.getString("Complemento")); } */ //delete /* BasicDBObject where = new BasicDBObject("Nome","Aninha"); //where nome = aninha colecao.remove(where); */ //update /* BasicDBObject where = new BasicDBObject("Nome","Pedrinho"); BasicDBObject set = new BasicDBObject("$set", new BasicDBObject("Nome","Pedrinho2")); colecao.update(where, set); */ } catch (UnknownHostException ex) { System.out.println(ex.getMessage()); } }
From source file:javawithmongo.JavaWithMongo.java
/** * @param args the command line arguments *///from w ww. j a v a 2 s. co m public static void main(String[] args) throws UnknownHostException, org.json.simple.parser.ParseException { // To directly connect to a single MongoDB server (note that this will not auto-discover the primary even // if it's a member of a replica set: MongoClient mongoClient = new MongoClient(); JSONParser parser = new JSONParser(); String ss = "[{\"school\":\"Unam Cch Plantel Sur\",\"schoolType\":\"High School\"},{\"school\":\"escuela secundaria diurna 281\",\"schoolType\":\"High School\",\"startYear\":2009},{\"school\":\"John F. Kennedy High School\",\"schoolType\":\"High School\"},{\"school\":\"UNAM FMVZ\",\"schoolType\":\"College\"},{\"school\":\"Facultad de Medicina Veterinaria y Zootecnia UNAM\",\"schoolType\":\"Graduate School\"}]"; Object obj = parser.parse(ss); JSONArray array = (JSONArray) obj; System.out.println("The 2nd element of array"); System.out.println(array.get(1)); System.out.println(); DB db = mongoClient.getDB("Gigya"); DBCollection coll = db.getCollection("datos"); BasicDBObject doc = new BasicDBObject("escuela", array); coll.save(doc); // Set<String> colls = db.getCollectionNames(); // // for (String s : colls) { // System.out.println(s); // } // // // DBObject myDoc = coll.findOne(); // System.out.println(myDoc.get("nombre")); }
From source file:juan.Estructuraimagen.java
public void intoMongo(ArrayList<ImageMongo> imagesMongo) throws UnknownHostException { int imheight = 0; int imwidth = 0; String immake = ""; int imdatetime = 0; int tamano = 0; //conectamos a la base de datos MongoClient mongoClient; mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("mydb"); //BORRAMOS LA BASE DE DATOS PARA QUE NO HAYA ELEMENTOS DUPLICADOS db.dropDatabase();/*from w w w .j a v a 2s . co m*/ DBCollection modfecha = db.getCollection("modelo-fecha"); DBCollection modtam = db.getCollection("modelo-tamao"); DBCollection modres = db.getCollection("modelo-resolucion"); DBCollection tamfecha = db.getCollection("tamano-fecha"); //recuperamos imagenes Iterator<ImageMongo> nombreIterator = imagesMongo.iterator(); BasicDBObject docmf1; BasicDBObject docmt1; BasicDBObject docmr1; BasicDBObject doctf1; while (nombreIterator.hasNext()) { ImageMongo elem = nombreIterator.next(); if (elem.getTags() != null) { Iterator<Itag> nombreItag = elem.getTags().iterator(); imheight = 0; imwidth = 0; immake = ""; imdatetime = 0; while (nombreItag.hasNext()) { Itag elemtag = nombreItag.next(); switch (elemtag.getName()) { case "Image Height": imheight = Integer.parseInt(elemtag.getValue()); break; case "Image Width": imwidth = Integer.parseInt(elemtag.getValue()); break; case "Make": immake = elemtag.getValue(); break; case "Date/Time": imdatetime = Integer.parseInt(elemtag.getValue()); break; } } tamano = Integer.parseInt(elem.getSize()); //insertamos un docuemnto en la coleccion docmf1 = new BasicDBObject(); docmf1.put("nombre", elem.getName()); docmf1.put("fecha", imdatetime); docmf1.put("ruta", elem.getRute().getName()); docmf1.put("marca", immake); modfecha.insert(docmf1); docmt1 = new BasicDBObject(); docmt1.put("nombre", elem.getName()); docmt1.put("tamano", tamano); docmt1.put("ruta", elem.getRute().getName()); docmt1.put("marca", immake); modtam.insert(docmt1); docmr1 = new BasicDBObject(); docmr1.put("nombre", elem.getName()); docmr1.put("height", imheight); docmr1.put("width", imwidth); docmr1.put("ruta", elem.getRute().getName()); docmr1.put("marca", immake); modres.insert(docmr1); doctf1 = new BasicDBObject(); doctf1.put("nombre", elem.getName()); doctf1.put("fecha", imdatetime); doctf1.put("ruta", elem.getRute().getName()); doctf1.put("tamano", tamano); tamfecha.insert(doctf1); } } }
From source file:kiaanfx.Kiaanfx.java
private static void getBuy() { try {//www . j a v a2s . c o m MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("kiaan"); DBCollection coll = db.getCollection("buy"); //aggregate DBObject unwind = new BasicDBObject("$unwind", "$items"); //$group DBObject group_id = new BasicDBObject("_id", "$_id"); group_id.put("num", "$num"); group_id.put("person_id", "$person_id"); group_id.put("discount", "$discount"); group_id.put("increase", "$increase"); //$group -> $multiply BasicDBList args = new BasicDBList(); args.add("$items.value"); args.add("$items.price"); DBObject multiply = new BasicDBObject("$multiply", args); //$group -> $sum // DBObject group_sum = new BasicDBObject("$sum", multiply); DBObject group_field = new BasicDBObject(); group_field.put("_id", group_id); group_field.put("total", new BasicDBObject("$sum", multiply)); DBObject group = new BasicDBObject("$group", group_field); //$project DBObject project_field = new BasicDBObject("_id", "$_id._id"); project_field.put("person_id", "$_id.person_id"); project_field.put("num", "$_id.num"); BasicDBList arr = new BasicDBList(); arr.add("$total"); arr.add("$_id.discount"); arr.add("$_id.increase"); DBObject field_add = new BasicDBObject("$add", arr); project_field.put("sum", field_add); DBObject project = new BasicDBObject("$project", project_field); DBObject sort = new BasicDBObject("$sort", new BasicDBObject("_id", 1)); List<DBObject> pipeline = Arrays.asList(unwind, group, project, sort); // AggregationOutput output = coll.aggregate(pipeline); // for (DBObject result : output.results()) { // System.out.println(result); // } AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100) .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build(); BasicDBObject dbo = new BasicDBObject(); BasicDBList dbl = new BasicDBList(); Cursor cursor = coll.aggregate(pipeline, aggregationOptions); // DBCollection person_col = db.getCollection("persons"); // BasicDBObject query = new BasicDBObject("items.personId",1); BasicDBObject fields = new BasicDBObject("items.$", 1).append("_id", false); // BasicDBList l_per = (BasicDBList) person_col.findOne(query, fields).get("items"); // BasicDBObject[] lightArr = l_per.toArray(new BasicDBObject[0]); // System.out.println(lightArr[0].get("_id")); // System.out.println(lightArr[0].get("first_name")); // BasicDBList result = new BasicDBList(); while (cursor.hasNext()) { dbo = (BasicDBObject) cursor.next(); // System.out.println(dbo.toString()); DBObject query = new BasicDBObject("items._id", (ObjectId) dbo.get("person_id")); BasicDBList lst_person = (BasicDBList) person_col.findOne(query, fields).get("items"); BasicDBObject[] lightArr = lst_person.toArray(new BasicDBObject[0]); // System.out.println(lightArr[0].get("first_name")); Date date = ((ObjectId) lightArr[0].get("_id")).getDate(); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); persianCalendar persianCalendar = new persianCalendar(calendar); dbo.put("date", persianCalendar.getNumericDateFormatWithTime()); dbo.put("personId", lightArr[0].get("personId").toString()); dbo.put("first_name", lightArr[0].get("first_name").toString()); dbo.put("last_name", lightArr[0].get("last_name").toString()); data.add(new Person(dbo.get("num").toString(), dbo.get("date").toString(), dbo.get("personId").toString(), dbo.get("first_name").toString(), dbo.get("last_name").toString())); // buy_data.add(new buys(dbo.get("num").toString(), // dbo.get("date").toString(), // dbo.get("personId").toString(), // dbo.get("first_name").toString(), // dbo.get("last_name").toString(), // dbo.get("sum").toString() // )); dbo.remove("person_id"); // result.add(dbo); // System.out.println(dbo.get("first_name")); } System.out.println(dbo.toString()); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } }
From source file:kiaanfx.Kiaanfx.java
public static void fill() { try {// www .j av a 2s . co m MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("test"); DBCollection coll = db.getCollection("table"); DBCursor cursor = coll.find(); DBObject obj; while (cursor.hasNext()) { obj = cursor.next(); // data.add(new Person((String) obj.get("first_name"), // (String) obj.get("last_name"), (String) obj.get("email"))); System.out.println(obj.get("_id")); // System.out.println(JSON.serialize(obj)); } } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } }
From source file:lab2sdindexservice.IndexService.java
public static void main(String args[]) throws IOException { //Variables para el Caching Service ServerSocket acceptSocket;//from w w w . j a v a 2 s .c om String[] LineaParticiones; String[] LineaCantResultados; String[] LineaIp; String[] LineaCachingPuerto; String[] LineaPuerto; String ipCaching; String puertoCaching; String puerto; int canTpart; int cantResult; MongoClient mongoClient = new MongoClient(); DB db = mongoClient.getDB("LabSD"); try { //Config tiene los parametros de configuracion del cache File archivo = new File("Config.txt"); FileReader fr = new FileReader(archivo); BufferedReader br = new BufferedReader(fr); //Lineas del Config.txt //Linea 1 tiene la cantidad de particiones de la bd String linea1 = br.readLine(); LineaParticiones = linea1.split(" "); canTpart = Integer.parseInt(LineaParticiones[1]); //Linea 2 tiene la cantidad de resultados que se desean mostrar como respuesta String linea2 = br.readLine(); LineaCantResultados = linea2.split(" "); cantResult = Integer.parseInt(LineaCantResultados[1]); //Linea 3 obtiene la ip del Caching Service String linea3 = br.readLine(); LineaIp = linea3.split(" "); ipCaching = LineaIp[1]; //Linea 4 obtiene el puerto del Caching Service String linea4 = br.readLine(); LineaCachingPuerto = linea4.split(" "); puertoCaching = LineaCachingPuerto[1]; //Linea 5 obtiene el puerto para recibir del Front Service String linea5 = br.readLine(); LineaPuerto = linea5.split(" "); puerto = LineaCachingPuerto[1]; fr.close(); //Validacion de parametros del config //Si los parametros son menores a 1, el caching service no corre if (canTpart < 1 || cantResult < 1) { System.out.println("Ingrese los parametros de forma correcta"); } else { System.out.println("Inicializando Index Service... "); try { //Socket para Recibir mensajes del FS acceptSocket = new ServerSocket(Integer.parseInt(puerto)); Socket socketCaching; //Socket para enviar al caching System.out.print("Server is running..."); System.out.println("\t[OK]\n"); int idSession = 0; while (true) { Socket connectionSocket; //Socket listo para recibir connectionSocket = acceptSocket.accept(); System.out.println("Nueva conexin entrante: " + connectionSocket); //Por cada conexion, se inicia un hilo (new Thread(new HiloIndexService(connectionSocket, ipCaching, puertoCaching, idSession, db, canTpart, cantResult))).start(); idSession++; } } catch (IOException ex) { Logger.getLogger(IndexService.class.getName()).log(Level.SEVERE, null, ex); } } } catch (Exception e) { //Catch de excepciones System.err.println("Ocurrio un error: " + e.getMessage()); } }
From source file:laboratorio_2_sd.Laboratorio_2_SD.java
public static void main(String[] args) throws Exception { //archivo de configuracion File archivo = new File("config.ini"); FileReader fr = new FileReader(archivo); BufferedReader br = new BufferedReader(fr); String linea = br.readLine(); int cantParticiones = Integer.parseInt(linea); linea = br.readLine();/*from w w w . j a v a2 s . c o m*/ String[] data = linea.split("\n"); String rutaDocumentos = data[0]; linea = br.readLine(); data = linea.split("\n"); String rutaStopwords = data[0]; if (imprime) System.out.println("Se configura con:\n- Particiones: " + cantParticiones + "\n- Ruta Documentos: '" + rutaDocumentos + "'\n- Ruta StopWords: '" + rutaStopwords + "'\n"); //Archivo stopwords File archivo3 = new File(rutaStopwords); FileReader fr3 = new FileReader(archivo3); BufferedReader br3 = new BufferedReader(fr3); ArrayList<String> stopwords = new ArrayList<>(); if (imprime) { System.out.println("StopWords: \n"); int contador = 0; while ((linea = br3.readLine()) != null && linea.length() != 0) {//mientras no sea EOF stopwords.add(linea); if (contador < 9) { System.out.print(linea + " "); contador++; } else if (contador == 9) { contador = 0; System.out.println(linea); } } System.out.println(""); } //Crea db y tablas MongoClient mongoClient = new MongoClient("localhost", 27017); mongoClient.dropDatabase("indexDB"); DB db = mongoClient.getDB("indexDB"); mongoClient.setWriteConcern(WriteConcern.JOURNALED); db.setWriteConcern(WriteConcern.JOURNALED); DBCollection colDocumentos = db.getCollection("Documentos"); DBCollection colIndiceInvertido = db.getCollection("IndiceInvertido"); DBCollection colVocabulario = db.getCollection("Vocabulario"); colDocumentos.createIndex(new BasicDBObject("idDoc", 1)); colIndiceInvertido.createIndex(new BasicDBObject("idPalabra", 1)); colVocabulario.createIndex(new BasicDBObject("palabra", 1)); //Archivo de documentos File archivo2 = new File(rutaDocumentos); FileReader fr2 = new FileReader(archivo2); BufferedReader br2 = new BufferedReader(fr2); int idDoc = 0; int idPalabraActual = 0; while ((linea = br2.readLine()) != null && !linea.contains("</mediawiki>")) {//mientras no sea EOF while (!linea.contains("<page>")) { linea = br2.readLine(); } //guarda el titulo linea = br2.readLine(); int indice = linea.indexOf(">"); String sub = linea.substring(indice + 1); indice = sub.indexOf("<"); String titulo = sub.substring(0, indice); //guarda el username while (!linea.contains("<username>")) { linea = br2.readLine(); } indice = linea.indexOf(">"); sub = linea.substring(indice + 1); indice = sub.indexOf("<"); String username = sub.substring(0, indice); while (linea.contains("<text") == false) { linea = br2.readLine(); } //Aqui comienza a leer el contenido del documento ArrayList<String> palabrasTemp = new ArrayList<String>(); while (linea.contains("</text>") == false) { linea = br2.readLine(); if (!linea.contains("</text>")) { StringTokenizer st = new StringTokenizer(linea, " #%_-*.,;:|/\\(){}[]=&+'\"?!"); while (st.hasMoreTokens()) { String palabra = st.nextToken(); palabra = palabra.toLowerCase(); if (palabra.length() > 1 && !stopwords.contains(palabra)) { palabrasTemp.add(palabra); } } } } Documento docTemp = new Documento(idDoc, palabrasTemp, titulo, username); if (imprime) docTemp.print(); //Se agrega el documento directamente a la coleccion documentos colDocumentos.insert(docTemp.toDBObject()); for (int i = 0; i < docTemp.cantPalabras; i++) { String palabra = docTemp.palabras.get(i); if (imprime) System.out.println("***********************"); if (imprime) System.out.println("Palabra: " + palabra); //revisa si la palabra esta en la coleccion vocabulario DBCursor cursor = colVocabulario.find((DBObject) new BasicDBObject("palabra", palabra)); if (cursor.hasNext()) { //si esta if (imprime) System.out.println("Esta en vocabulario"); Vocabulario vocTemp = new Vocabulario((BasicDBObject) cursor.next()); if (imprime) System.out.println("idPalabra: " + vocTemp.idPalabra); DBCursor cursor2 = colIndiceInvertido .find((DBObject) new BasicDBObject("idPalabra", vocTemp.idPalabra)); BasicDBObject find = (BasicDBObject) cursor2.next(); IndiceInvertido indiceTemp = new IndiceInvertido(find); //revisa si ya est ingresado el documento actual en el indiceInvertido int contador = 0; int frec = 0; for (int j = 0; j < indiceTemp.frecuencias.size(); j++) { if (indiceTemp.frecuencias.get(j).idDocumento == idDoc) { contador = 1; frec = indiceTemp.frecuencias.get(j).frecuencia; break; } } if (contador == 1) { //si encontro el id del documento actual if (imprime) System.out.println("Esta en indice invertido"); //actualizar frecuencia en indice Invertido indiceTemp.ActualizarFrecuencias(frec + 1, idDoc); colIndiceInvertido.update(find, indiceTemp.toDBObject(), false, true); if (imprime) indiceTemp.print(); } else {//si no est if (imprime) System.out.println("No est en indice invertido"); //actualizar la cantidad de documentos del vocabulario vocTemp.cantDocumentos++; colVocabulario.insert(vocTemp.toDBObject()); if (imprime) vocTemp.print(); //agregar nueva tupla de frecuencia/idDoc a indice indiceTemp.ActualizarFrecuencias(1, idDoc); if (imprime) indiceTemp.print(); colIndiceInvertido.insert(indiceTemp.toDBObject()); } } else {//no esta if (imprime) System.out.println("No esta en vocabulario\nInserta nuevo elemento"); if (idDoc == 0 && i == 0) { //no se ha insertado ningun dato //inserta palabra en vocabulario Vocabulario vocTemp = new Vocabulario(palabra, 0, 1); colVocabulario.insert(vocTemp.toDBObject()); if (imprime) vocTemp.print(); //inserta entrada en indice invertido IndiceInvertido indiceTemp = new IndiceInvertido(vocTemp.idPalabra, 1, idDoc); colIndiceInvertido.insert(indiceTemp.toDBObject()); if (imprime) indiceTemp.print(); idPalabraActual++; } else { //se obtiene un nuevo id //se inserta a vocabulario Vocabulario vocTemp = new Vocabulario(palabra, idPalabraActual, 1); colVocabulario.insert(vocTemp.toDBObject()); if (imprime) vocTemp.print(); //se inserta a indice invertido IndiceInvertido indiceTemp = new IndiceInvertido(vocTemp.idPalabra, 1, idDoc); if (imprime) indiceTemp.print(); colIndiceInvertido.insert(indiceTemp.toDBObject()); idPalabraActual++; } } } idDoc++; while (!linea.contains("</page>")) { linea = br2.readLine(); } pasarGarbageCollector(); } }