Example usage for com.mongodb DBCollection drop

List of usage examples for com.mongodb DBCollection drop

Introduction

In this page you can find the example usage for com.mongodb DBCollection drop.

Prototype

public void drop() 

Source Link

Document

Drops (deletes) this collection from the database.

Usage

From source file:com.ibm.sae.LoadDreamHomeDB.java

/***************************************************************/
 private static void loadOffice(DB db, DBCollection coll) {
     System.out.println("LoadDreamHomeDB:loadOffice begins");

     coll.drop();

     DBObject officeDoc = new BasicDBObject("officeId", 2999).append("officeName", "Valley North")
             .append("officeManager", "Erlich Bachman")
             .append("officeAddr", new BasicDBObject("address", "223 Mountain Drive")
                     .append("city", "Buena Vista").append("state", "California").append("zip", "65746"))
             .append("numProperties", 0);
     WriteResult wr = coll.insert(officeDoc, WriteConcern.ACKNOWLEDGED);

     System.out.println("LoadDreamHomeDB:loadOffice ends");
 }

From source file:com.ibm.sae.LoadDreamHomeDB.java

/***************************************************************/
 private static void loadProperty(DB db, DBCollection coll) {
     System.out.println("LoadDreamHomeDB:loadOffice begins");

     coll.drop();

     DBObject propertyDoc = new BasicDBObject("propertyId", 2000)
             .append("location",
                     new BasicDBObject("address", "1024 College").append("city", "Wheaton")
                             .append("state", "California").append("zip", "76857")
                             .append("longitude", "35.601623").append("latitude", "-78.245908"))
             .append("sqFeet", 2895).append("numBeds", 4).append("numBaths", 3)
             .append("description", "Two blocks from university").append("askingPrice", 789900.00);
     WriteResult wr = coll.insert(propertyDoc, WriteConcern.ACKNOWLEDGED);

     DBObject propertyDoc2 = new BasicDBObject("propertyId", 2001)
             .append("location",
                     new BasicDBObject("address", "435 Weston").append("city", "Springfield")
                             .append("state", "California").append("zip", "76857")
                             .append("longitude", "36.507623").append("latitude", "-79.145509"))
             .append("sqFeet", 3200).append("numBeds", 5).append("numBaths", 3)
             .append("description", "Nice cottage by lake").append("askingPrice", 569900.00);
     WriteResult wr2 = coll.insert(propertyDoc2, WriteConcern.ACKNOWLEDGED);

     DBObject propertyDoc3 = new BasicDBObject("propertyId", 2002)
             .append("location",
                     new BasicDBObject("address", "2240 Berlin").append("city", "Florence")
                             .append("state", "California").append("zip", "76857")
                             .append("longitude", "31.086579").append("latitude", "-72.357987"))
             .append("sqFeet", 3950).append("numBeds", 5).append("numBaths", 5)
             .append("description", "Mansion in the city").append("askingPrice", 645800.00);
     WriteResult wr3 = coll.insert(propertyDoc3, WriteConcern.ACKNOWLEDGED);

     System.out.println("LoadDreamHomeDB:loadProperty ends");
 }

From source file:com.ijuru.ijambo.dao.WordDAO.java

License:Open Source License

/**
 * Removes all words
 */
public void removeAll() {
    DBCollection words = db.getCollection("words");
    words.drop();
}

From source file:com.ikanow.infinit.e.data_model.store.MongoDbManager.java

License:Apache License

@SuppressWarnings("deprecation")
public static void main(String[] args) throws UnknownHostException {
    MongoClient mc = new MongoClient(args[0]);
    long tnow = 0;
    DB db = mc.getDB("test");
    DBCollection test = db.getCollection("test123");
    BasicDBObject outObj = new BasicDBObject();
    int ITS = 1000;
    test.drop();

    boolean checkPerformance = false;
    boolean checkFunctionality = false;
    boolean checkErrors = false;

    // 1] Performance

    if (checkPerformance) {

        // ack'd// w  w w.j a  v  a  2s . co m
        db.setWriteConcern(WriteConcern.ACKNOWLEDGED);
        test.drop();
        tnow = new Date().getTime();
        for (int i = 0; i < ITS; ++i) {
            outObj.remove("_id");
            outObj.put("val", i);
            test.save(outObj);
        }
        tnow = new Date().getTime() - tnow;
        System.out.println("1: Ack'd: " + tnow);

        // un ack'd
        db.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
        test.drop();
        tnow = new Date().getTime();
        outObj = new BasicDBObject();
        for (int i = 0; i < ITS; ++i) {
            outObj.remove("_id");
            outObj.put("val", i);
            test.save(outObj);
        }
        tnow = new Date().getTime() - tnow;
        System.out.println("2: unAck'd: " + tnow);

        // un ack'd but call getLastError
        db.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
        test.drop();
        tnow = new Date().getTime();
        outObj = new BasicDBObject();
        for (int i = 0; i < ITS; ++i) {
            outObj.remove("_id");
            outObj.put("val", i);
            test.save(outObj);
            db.getLastError();
        }
        tnow = new Date().getTime() - tnow;
        test.drop();
        System.out.println("3: unAck'd but GLEd: " + tnow);

        // ack'd override
        db.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
        test.drop();
        tnow = new Date().getTime();
        outObj = new BasicDBObject();
        for (int i = 0; i < ITS; ++i) {
            outObj.remove("_id");
            outObj.put("val", i);
            test.save(outObj, WriteConcern.ACKNOWLEDGED);
            db.getLastError();
        }
        tnow = new Date().getTime() - tnow;
        System.out.println("4: unAck'd but ACKd: " + tnow);

        // Performance Results:
        // 2.6) (unack'd 100ms ... ack'd 27000)
        // 2.4) (same)
    }

    // 2] Functionality

    if (checkFunctionality) {

        // Unack:
        db.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
        WriteResult wr = test.update(new BasicDBObject(),
                new BasicDBObject(DbManager.set_, new BasicDBObject("val2", "x")), false, true);
        CommandResult cr = db.getLastError();
        System.out.println("UNACK: wr: " + wr);
        System.out.println("UNACK: cr: " + cr);

        // bonus, check that we get N==0 when insert dup object
        WriteResult wr2 = test.insert(outObj);
        System.out.println("ACK wr2 = " + wr2.getN() + " all = " + wr2);
        CommandResult cr2 = db.getLastError();
        System.out.println("ACK cr2 = " + cr2);

        // Ack1:
        db.setWriteConcern(WriteConcern.ACKNOWLEDGED);
        wr = test.update(new BasicDBObject(), new BasicDBObject(DbManager.set_, new BasicDBObject("val3", "x")),
                false, true);
        cr = db.getLastError();
        System.out.println("ACK1: wr: " + wr);
        System.out.println("ACK1: cr: " + cr);

        // Ack2:
        db.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
        wr = test.update(new BasicDBObject(), new BasicDBObject(DbManager.set_, new BasicDBObject("val4", "x")),
                false, true, WriteConcern.ACKNOWLEDGED);
        cr = db.getLastError();
        System.out.println("ACK2: wr: " + wr);
        System.out.println("ACK2: cr: " + cr);

        // bonus, check that we get N==0 when insert dup object
        wr2 = test.insert(outObj);
        System.out.println("ACK wr2 = " + wr2.getN() + " all = " + wr2);

        // Functionality results:
        // 2.6: unack wr == N/A, otherwise both have "n", "ok"
        // 2.4: unack wr == N/A all other wrs + crs identical 
    }

    if (checkErrors) {

        //set up sharding
        DbManager.getDB("admin").command(new BasicDBObject("enablesharding", "test"));
        // Ack:
        try {
            test.drop();
            test.createIndex(new BasicDBObject("key", 1));
            BasicDBObject command1 = new BasicDBObject("shardcollection", "test.test123");
            command1.append("key", new BasicDBObject("key", 1));
            DbManager.getDB("admin").command(command1);

            db.setWriteConcern(WriteConcern.ACKNOWLEDGED);
            outObj = new BasicDBObject("key", "test");
            test.save(outObj);
            WriteResult wr = test.update(new BasicDBObject(),
                    new BasicDBObject(DbManager.set_, new BasicDBObject("key", "test2")));
            System.out.println("ACK wr = " + wr);
        } catch (Exception e) {
            System.out.println("ACK err = " + e.toString());
        }

        // UnAck:
        try {
            test.drop();
            test.createIndex(new BasicDBObject("key", 1));
            BasicDBObject command1 = new BasicDBObject("shardcollection", "test.test123");
            command1.append("key", new BasicDBObject("key", 1));
            DbManager.getDB("admin").command(command1);

            db.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
            outObj = new BasicDBObject("key", "test");
            test.save(outObj);
            WriteResult wr = test.update(new BasicDBObject(),
                    new BasicDBObject(DbManager.set_, new BasicDBObject("key", "test2")), false, false,
                    WriteConcern.ACKNOWLEDGED);
            System.out.println("ACK override wr = " + wr);
        } catch (Exception e) {
            System.out.println("ACK override  err = " + e.toString());
        }

        // UnAck:
        try {
            test.drop();
            test.createIndex(new BasicDBObject("key", 1));
            BasicDBObject command1 = new BasicDBObject("shardcollection", "test.test123");
            command1.append("key", new BasicDBObject("key", 1));
            DbManager.getDB("admin").command(command1);

            db.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
            outObj = new BasicDBObject("key", "test");
            test.save(outObj);
            WriteResult wr = test.update(new BasicDBObject(),
                    new BasicDBObject(DbManager.set_, new BasicDBObject("key", "test2")));
            System.out.println("UNACK wr = " + wr);
        } catch (Exception e) {
            System.out.println("UNACK err = " + e.toString());
        }

        // UnAck + GLE:
        try {
            test.drop();
            test.createIndex(new BasicDBObject("key", 1));
            BasicDBObject command1 = new BasicDBObject("shardcollection", "test.test123");
            command1.append("key", new BasicDBObject("key", 1));
            DbManager.getDB("admin").command(command1);

            db.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
            outObj = new BasicDBObject("key", "test");
            test.save(outObj);
            WriteResult wr = test.update(new BasicDBObject(),
                    new BasicDBObject(DbManager.set_, new BasicDBObject("key", "test2")));
            CommandResult cr = db.getLastError();
            System.out.println("UNACK GLE wr = " + wr);
            System.out.println("UNACK GLE cr = " + cr);
        } catch (Exception e) {
            System.out.println("UNACK GLE err = " + e.toString());
        }

        // Error handling:

        // 2.6:
        // Ack - exception
        // Ack override - exception
        // UnAck - no error given
        // UnAck + GLE  - gle error

        // 2.4:
        // Ack - exception
        // Ack override - exception
        // UnAck - no error given
        // UnAck + GLE  - gle error

    }
}

From source file:com.jaspersoft.mongodb.importer.MongoDbImporter.java

License:Open Source License

public void importTable(String tableName) throws Exception {
    createConnection();//from  ww  w . ja v  a2s .c om
    logger.info("Initialize import");
    ResultSet resultSet = null;
    List<DBObject> objectsList = new ArrayList<DBObject>();
    try {
        resultSet = statement.executeQuery("SELECT * FROM " + tableName);
        ResultSetMetaData metaData = resultSet.getMetaData();
        int index, columnCount = metaData.getColumnCount(), count = 0;
        logger.info("Importing rows");
        DBCollection collection = null;
        if (!mongodbConnection.getMongoDatabase().collectionExists(tableName)) {
            logger.info("Collection \"" + tableName + "\" doesn't exist");
            DBObject options = new BasicDBObject("capped", false);
            collection = mongodbConnection.getMongoDatabase().createCollection(tableName, options);
        } else {
            logger.info("Collection \"" + tableName + "\" exists");
            collection = mongodbConnection.getMongoDatabase().getCollectionFromString(tableName);
            collection.drop();
            logger.info("Collection \"" + tableName + "\" was cleaned up");
        }
        Object value;
        DBObject newObject;
        while (resultSet.next()) {
            newObject = new BasicDBObject();
            for (index = 1; index <= columnCount; index++) {
                value = resultSet.getObject(index);
                if (value != null) {
                    newObject.put(metaData.getColumnName(index), value);
                }
            }
            objectsList.add(newObject);
            count++;
            if (count % 100 == 0) {
                logger.info("Processed: " + count);
                logger.info("Result: " + collection.insert(objectsList).getField("ok"));
                objectsList.clear();
            }
        }
        if (objectsList.size() > 0) {
            collection.insert(objectsList);
            logger.info("Result: " + collection.insert(objectsList).getField("ok"));
            objectsList.clear();
        }
        logger.info("Rows added: " + count);
        logger.info("Import done");
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }
    }
}

From source file:com.jaspersoft.mongodb.importer.MongoDbSimpleImporter.java

License:Open Source License

private void populate(MongoDbConnection connection, String collectionName, Resource scriptResource)
        throws JRException {
    DBCollection collection = null;
    DB mongoDatabase = null;//from   w ww .  j av  a 2s. c  o  m
    try {
        mongoDatabase = connection.getMongoDatabase();
        if (!mongoDatabase.collectionExists(collectionName)) {
            logger.info("Collection \"" + collectionName + "\" doesn't exist");
            DBObject options = new BasicDBObject("capped", false);
            collection = mongoDatabase.createCollection(collectionName, options);
        } else {
            logger.info("Collection \"" + collectionName + "\" exists");
            collection = mongoDatabase.getCollectionFromString(collectionName);
            collection.drop();
            logger.info("Collection \"" + collectionName + "\" was cleaned up");
        }
    } catch (MongoException e) {
        logger.error(e);
    }

    if (mongoDatabase == null) {
        throw new JRException(
                "Failed connection to mongoDB database: " + connection.getMongoURIObject().getDatabase());
    }

    FileInputStream fileInputStream = null;
    InputStreamReader inputStreamReader = null;
    BufferedReader reader = null;
    try {
        inputStreamReader = new InputStreamReader(scriptResource.getInputStream());
        reader = new BufferedReader(inputStreamReader);
        StringBuilder stringBuilder = new StringBuilder();
        String currentLine;
        while ((currentLine = reader.readLine()) != null) {
            stringBuilder.append(currentLine);
        }
        Object parseResult = JSON.parse(stringBuilder.toString());
        if (!(parseResult instanceof BasicDBList)) {
            throw new JRException(
                    "Unsupported type: " + parseResult.getClass().getName() + ". It must be a list");
        }
        BasicDBList list = (BasicDBList) parseResult;
        List<DBObject> objectsList = new ArrayList<DBObject>();
        for (int index = 0; index < list.size(); index++) {
            objectsList.add((DBObject) list.get(index));
        }
        collection.insert(objectsList);
        logger.info("Collection count: " + collection.count() + "\nSuccessfully populated collection: "
                + collectionName);
    } catch (UnsupportedEncodingException e) {
        logger.error(e);
    } catch (IOException e) {
        logger.error(e);
    } finally {
        if (fileInputStream != null) {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                logger.error(e);
            }
        }
        if (inputStreamReader != null) {
            try {
                inputStreamReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.kurniakue.trxreader.data.CustomerD.java

@Override
public void reset() {
    Set<String> collectionNames = KurniaKueDb.getDb().getCollectionNames();
    if (collectionNames.contains(COLLECTION_NAME)) {
        DBCollection collection = KurniaKueDb.getDb().getCollection(COLLECTION_NAME);
        collection.drop();
    }/*from   w w w .  j a  v a2 s  . com*/
}

From source file:com.lakeside.data.mongo.MongoDbRestore.java

License:Open Source License

protected void restore(CollectionInfo info) {
    try {//from w w  w .ja  v  a 2s .c  om
        String collectionName = info.getName();
        System.out.println("restoring collection " + collectionName);
        File[] files = new File(INPUT_DIR).listFiles();
        if (files != null) {
            List<File> filesToProcess = new ArrayList<File>();
            for (File file : files) {
                String name = file.getName();
                int indexOf = name.indexOf(".bson");
                if (name.startsWith(collectionName) && indexOf > 0) {
                    String temp = name.substring(collectionName.length() + 1, indexOf);
                    if (temp.matches("\\d*")) {
                        filesToProcess.add(file);
                    }
                }
            }
            Collections.sort(filesToProcess, new FilenameComparator());
            if (DROP_EXISTING) {
                try {
                    System.out.println("Dropping collection " + collectionName);

                    DB db = MongoDBConnectionManager.getConnection(DATABASE_HOST, "local", DATABASE_USER_NAME,
                            DATABASE_PASSWORD);

                    DBCollection coll = db.getCollection(collectionName);
                    coll.drop();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            long count = 0;
            long startTime = System.currentTimeMillis();
            long lastOutput = System.currentTimeMillis();
            for (File file : filesToProcess) {
                System.out.println("restoring file " + file.getName() + " to collection " + collectionName);
                InputStream inputStream = null;
                try {
                    if (file.getName().endsWith(".gz")) {
                        inputStream = new GZIPInputStream(new FileInputStream(file));
                    } else {
                        inputStream = new BufferedInputStream(new FileInputStream(file));
                    }
                    BSONDecoder decoder = new DefaultDBDecoder();
                    while (true) {
                        if (inputStream.available() == 0) {
                            break;
                        }
                        BSONObject obj = decoder.readObject(inputStream);
                        if (obj == null) {
                            break;
                        }
                        write(info, new BasicDBObject((BasicBSONObject) obj));
                        count++;

                        long duration = System.currentTimeMillis() - lastOutput;
                        if (duration > REPORT_DURATION) {
                            report(collectionName, count, System.currentTimeMillis() - startTime);
                            lastOutput = System.currentTimeMillis();
                        }
                    }
                } catch (java.io.EOFException e) {
                    break;
                } finally {
                    inputStream.close();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.liferay.mongodb.hook.listeners.ExpandoTableListener.java

License:Open Source License

@Override
public void onAfterRemove(ExpandoTable expandoTable) {
    DB db = MongoDBUtil.getDB(expandoTable.getCompanyId());

    String tableName = MongoDBUtil.getCollectionName(expandoTable.getClassName(), expandoTable.getName());

    if (db.collectionExists(tableName)) {
        DBCollection dbCollection = db.getCollection(tableName);

        dbCollection.drop();
    }/*from w  w  w  . j  a  v  a 2s.  co  m*/
}

From source file:com.linuxbox.util.mongodb.Dropper.java

License:Open Source License

public static void dropCollection(String dbName, String collection)
        throws UnknownHostException, MongoException {
    Mongo m = new Mongo();
    DB db = m.getDB(dbName);/*from w  w  w . java2  s.  c om*/
    DBCollection c = db.getCollection(collection);
    c.drop();
}