Example usage for com.mongodb MongoClient dropDatabase

List of usage examples for com.mongodb MongoClient dropDatabase

Introduction

In this page you can find the example usage for com.mongodb MongoClient dropDatabase.

Prototype

public void dropDatabase(final String dbName) 

Source Link

Document

Drops the database if it exists.

Usage

From source file:br.bireme.scl.JoinTitle.java

License:Open Source License

public JoinTitle(final String host, final int port) throws UnknownHostException {
    if (host == null) {
        throw new NullPointerException("host");
    }/*from w w w. j  a v a  2  s  .  c o m*/
    if (port <= 0) {
        throw new IllegalArgumentException("port <= 0");
    }

    final MongoClient mongoClient = new MongoClient(host, port);

    mongoClient.dropDatabase(DB_NAME);
    db = mongoClient.getDB(DB_NAME);
}

From source file:com.stratio.tests.ATExampleMongoDB.java

License:Apache License

@BeforeClass
public void setUp() throws UnknownHostException {
    MongoClient mongoClient = new MongoClient(mongoHost, mongoPort);
    mongoClient.dropDatabase(dataBase);
    DB db = mongoClient.getDB(dataBase);
    DBCollection tabletest = db.getCollection("tabletest");
    // DBCollection tabletest = db.createCollection("tabletest");
    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
    format.setTimeZone(TimeZone.getTimeZone("CET"));
    for (int i = 0; i < 10; i++) {
        Date parsedDate = null;//from ww w.ja v  a  2s.c o  m
        String fecha = i + "/" + i + "/200" + i;
        try {
            parsedDate = format.parse(fecha);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(new java.sql.Date(parsedDate.getTime()).toString());
        BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start().add("ident", i)
                .add("name", "name_" + i).add("money", 10.2 + i).add("new", true)
                .add("date", new java.sql.Date(parsedDate.getTime()));
        tabletest.insert(documentBuilder.get());
    }
    //   DBObject aux = tabletest.findOne();
    //  java.sql.Date aux1 = (java.sql.Date)aux.get("date");
    mongoClient.close();
    String connector = "Mongo";
    //Preparamos las cositas para compartir
    ThreadProperty.set("Host", "127.0.0.1");
    ThreadProperty.set("Connector", connector);

}

From source file:com.stratio.tests.ATExampleMongoDB.java

License:Apache License

@AfterClass
public void cleanUp() throws UnknownHostException {
    MongoClient mongoClient = new MongoClient(mongoHost, mongoPort);
    mongoClient.dropDatabase(dataBase);
}

From source file:edu.umass.cs.gnsserver.database.MongoRecords.java

License:Apache License

/**
 * @param nodeID/* ww  w  . j a  v a  2 s.c  o m*/
 */
public static void dropNodeDatabase(String nodeID) {
    MongoClient mongoClient;
    try {
        mongoClient = new MongoClient("localhost");
    } catch (UnknownHostException e) {
        DatabaseConfig.getLogger().log(Level.SEVERE, "Unable to open Mongo DB: {0}", e.getMessage());
        return;
    }
    String dbName = DBROOTNAME + sanitizeDBName(nodeID);
    mongoClient.dropDatabase(dbName);

    List<String> names = mongoClient.getDatabaseNames();
    for (String name : names) {
        if (name.startsWith(dbName)) {
            mongoClient.dropDatabase(name);
        }
    }

    System.out.println("Dropped DB " + dbName);
}

From source file:example.QuickTourAdmin.java

License:Apache License

public static void main(String[] args) throws Exception {

    // connect to the local database server 
    MongoClient mongoClient = new MongoClient();

    // Authenticate - optional
    // boolean auth = db.authenticate("foo", "bar");

    // get db names
    for (String s : mongoClient.getDatabaseNames()) {
        System.out.println(s);/* w  w w  . ja v  a2  s. c o m*/
    }

    // get a db
    DB db = mongoClient.getDB("com_mongodb_MongoAdmin");

    // do an insert so that the db will really be created.  Calling getDB() doesn't really take any
    // action with the server 
    db.getCollection("testcollection").insert(new BasicDBObject("i", 1));
    for (String s : mongoClient.getDatabaseNames()) {
        System.out.println(s);
    }

    // drop a database
    mongoClient.dropDatabase("com_mongodb_MongoAdmin");

    for (String s : mongoClient.getDatabaseNames()) {
        System.out.println(s);
    }
}

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();/*ww w . java2 s  .  co  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();
    }

}

From source file:org.apache.jackrabbit.oak.upgrade.cli.container.MongoNodeStoreContainer.java

License:Apache License

@Override
public void clean() throws IOException {
    MongoClientURI uri = new MongoClientURI(mongoUri);
    MongoClient client = new MongoClient(uri);
    client.dropDatabase(uri.getDatabase());
    blob.clean();//from   www  . j a  v a 2  s .  c o  m
}

From source file:org.codinjutsu.tools.mongo.logic.MongoManager.java

License:Apache License

public void dropDatabase(ServerConfiguration configuration, MongoDatabase selectedDatabase) {
    MongoClient mongo = null;
    try {//from  w ww  .  j a  v  a2  s  . com
        mongo = createMongoClient(configuration);
        mongo.dropDatabase(selectedDatabase.getName());
    } catch (UnknownHostException ex) {
        throw new ConfigurationException(ex);
    } finally {
        if (mongo != null) {
            mongo.close();
        }
    }
}

From source file:org.codinjutsu.tools.nosql.mongo.logic.SingleMongoClient.java

License:Apache License

public void dropDatabase(ServerConfiguration configuration, SingleMongoDatabase selectedDatabase) {
    MongoClient mongo = null;
    try {/* ww w.ja  v  a2  s.  co  m*/
        mongo = createMongoClient(configuration);
        mongo.dropDatabase(selectedDatabase.getName());
    } catch (UnknownHostException ex) {
        throw new ConfigurationException(ex);
    } finally {
        if (mongo != null) {
            mongo.close();
        }
    }
}

From source file:teste.mongo.example.QuickTourAdmin.java

License:Apache License

public static void main(String[] args) throws Exception {

    // connect to the local database server 
    MongoClient mongoClient = new MongoClient();

    /*/*w  w w  .  ja va  2  s  .c o m*/
    // Authenticate - optional
    MongoCredential credential = MongoCredential.createMongoCRCredential(userName, database, password);
    MongoClient mongoClient = new MongoClient(new ServerAddress(), Arrays.asList(credential));
    */

    System.out.println("##### DataBaseInitial");
    // get db names
    for (String s : mongoClient.getDatabaseNames()) {
        System.out.println(s);
    }

    // get a db
    DB db = mongoClient.getDB("mydb");

    System.out.println("##### With new DataBase MYDB");
    // do an insert so that the db will really be created.  Calling getDB() doesn't really take any
    // action with the server 
    db.getCollection("testcollection").insert(new BasicDBObject("i", 1));
    for (String s : mongoClient.getDatabaseNames()) {
        System.out.println(s);
    }

    // drop a database
    mongoClient.dropDatabase("mydb");

    System.out.println("##### DataBase drop MYDB");
    for (String s : mongoClient.getDatabaseNames()) {
        System.out.println(s);
    }

    // create a collection
    db = mongoClient.getDB("mydb");
    db.createCollection("testCollection", new BasicDBObject("capped", true).append("size", 1048576));

    System.out.println("##### ListAllCollection MYDB");
    // List all collections
    for (String s : db.getCollectionNames()) {
        System.out.println(s);
    }

    // Dropping a collection
    DBCollection testCollection = db.getCollection("testCollection");
    testCollection.drop();
    System.out.println("##### ListAllCollection MYDB - Drop testCollection");
    System.out.println(db.getCollectionNames());

    /* Indexes */
    // get a collection object to work with
    DBCollection coll = db.getCollection("testCollection");

    // drop all the data in it
    coll.drop();

    // create an index on the "i" field
    coll.createIndex(new BasicDBObject("i", 1));

    // Geospatial query
    coll.createIndex(new BasicDBObject("loc", "2dsphere"));

    BasicDBList coordinates = new BasicDBList();
    coordinates.put(0, -73.97);
    coordinates.put(1, 40.77);
    coll.insert(new BasicDBObject("name", "Central Park")
            .append("loc", new BasicDBObject("type", "Point").append("coordinates", coordinates))
            .append("category", "Parks"));

    coordinates.put(0, -73.88);
    coordinates.put(1, 40.78);
    coll.insert(new BasicDBObject("name", "La Guardia Airport")
            .append("loc", new BasicDBObject("type", "Point").append("coordinates", coordinates))
            .append("category", "Airport"));

    // Find whats within 500m of my location
    BasicDBList myLocation = new BasicDBList();
    myLocation.put(0, -73.965);
    myLocation.put(1, 40.769);
    DBObject myDoc = coll.findOne(new BasicDBObject("loc", new BasicDBObject("$near",
            new BasicDBObject("$geometry", new BasicDBObject("type", "Point").append("coordinates", myLocation))
                    .append("$maxDistance", 500))));
    System.out.println(myDoc.get("name"));

    // create a text index on the "content" field
    coll.createIndex(new BasicDBObject("content", "text"));

    coll.insert(new BasicDBObject("_id", 0).append("content", "textual content"));
    coll.insert(new BasicDBObject("_id", 1).append("content", "additional content"));
    coll.insert(new BasicDBObject("_id", 2).append("content", "irrelevant content"));

    // Find using the text index
    BasicDBObject search = new BasicDBObject("$search", "textual content -irrelevant");
    BasicDBObject textSearch = new BasicDBObject("$text", search);
    int matchCount = coll.find(textSearch).count();
    System.out.println("Text search matches: " + matchCount);

    // Find using the $language operator
    textSearch = new BasicDBObject("$text", search.append("$language", "english"));
    matchCount = coll.find(textSearch).count();
    System.out.println("Text search matches (english): " + matchCount);

    // Find the highest scoring match
    BasicDBObject projection = new BasicDBObject("score", new BasicDBObject("$meta", "textScore"));
    myDoc = coll.findOne(textSearch, projection);
    System.out.println("Highest scoring document: " + myDoc);

    // list the indexes on the collection
    List<DBObject> list = coll.getIndexInfo();
    for (final DBObject o : list) {
        System.out.println(o);
    }

    // clean up
    mongoClient.dropDatabase("mydb");
    mongoClient.close();
}