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.mebigfatguy.mongobrowser.actions.DeleteAction.java

License:Apache License

@Override
public void actionPerformed(ActionEvent e) {
    MongoTreeNode node = context.getSelectedNode();
    switch (node.getType()) {
    case Collection: {
        DBCollection collection = (DBCollection) node.getUserObject();
        collection.drop();
        MongoTreeNode dbNode = (MongoTreeNode) node.getParent();
        dbNode.remove(node);//w  w  w .  j  av a2  s  .  co  m
        DefaultTreeModel model = (DefaultTreeModel) context.getTree().getModel();
        model.nodeStructureChanged(dbNode);
    }
        break;

    case Object: {
        DBObject object = (DBObject) node.getUserObject();
        MongoTreeNode collectionNode = TreeUtils.findCollectionNode(node);
        DBCollection collection = (DBCollection) collectionNode.getUserObject();
        collection.remove(object);
        collectionNode.remove(node);
        DefaultTreeModel model = (DefaultTreeModel) context.getTree().getModel();
        model.nodeStructureChanged(collectionNode);
    }
        break;

    case KeyValue: {
        MongoTreeNode.KV kv = (MongoTreeNode.KV) node.getUserObject();
        String key = kv.getKey();
        if (!key.startsWith("_")) {
            MongoTreeNode objectNode = (MongoTreeNode) node.getParent();
            DBObject object = (DBObject) objectNode.getUserObject();
            object.removeField(key);
            MongoTreeNode collectionNode = TreeUtils.findCollectionNode(objectNode);
            DBCollection collection = (DBCollection) collectionNode.getUserObject();
            collection.save(object);
            objectNode.remove(node);
            DefaultTreeModel model = (DefaultTreeModel) context.getTree().getModel();
            model.nodeStructureChanged(objectNode);
        }
    }
        break;
    }
}

From source file:com.nlp.twitterstream.MongoUtil.java

License:Open Source License

/**
 * Drop Collection Removes all documents and indexes
 */
public void dropCollection(DBCollection collection) {

    collection.drop();
}

From source file:com.original.service.channel.config.Initializer.java

License:Open Source License

/**
 * /*from  w  ww .j  av  a  2  s.  c o  m*/
 * @param db
 * @param collectionName
 * @param fileName
 * @param force
 * @throws IOException
 */
private void initCollection(DB db, String collectionName, String fileName, boolean force) throws IOException {
    DBCollection collection = db.getCollection(collectionName);
    if (collection.getCount() > 0 && !force) {
        logger.info(collectionName + " had existed!");
        return;
    }

    if (force && collection.getCount() > 0) {
        collection.drop();
        logger.info("force to init, drop the collection:" + collectionName);
    }
    BufferedReader br = null;
    if (fileName.startsWith("/")) {
        InputStream is = Initializer.class.getResourceAsStream(fileName);
        br = new BufferedReader(new InputStreamReader(is));
    } else {
        br = new BufferedReader(new FileReader(fileName));
    }

    StringBuffer fileText = new StringBuffer();
    String line;
    while ((line = br.readLine()) != null) {
        fileText.append(line);
    }
    logger.info(collectionName + " Read:" + fileText);
    // System.out.println(profile);
    br.close();
    if (fileText != null) {
        // convert JSON to DBObject directly
        List<String> list = parseJsonItemsFile(fileText);
        for (String txt : list) {
            logger.info(collectionName + " init item:" + txt);
            DBObject dbObject = (DBObject) JSON.parse(txt);
            collection.insert(dbObject);
        }
    }
    logger.info(collectionName + " init Done:" + collection.count());
}

From source file:com.percona.LinkBench.MongoDBTestConfig.java

License:Apache License

static void dropTestTables(DB db, String testDB) throws MongoClientException {
    // get handles to the collections
    DBCollection linkColl = getOrCreateCollection(db, linktable);
    DBCollection nodeColl = getOrCreateCollection(db, nodetable);
    DBCollection countColl = getOrCreateCollection(db, counttable);
    DBCollection transColl = getOrCreateCollection(db, transtable);

    linkColl.drop();
    nodeColl.drop();/*from  www . ja v a 2s. c  o  m*/
    countColl.drop();
    transColl.drop();

}

From source file:com.sample.MyGroceryListServlet.java

License:Open Source License

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *///from w  w w  .  j  av  a 2  s  .c  om
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Reference: http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/#getting-started-with-java-driver

    String envVars = System.getenv("VCAP_SERVICES");

    DBObject dbO = (DBObject) JSON.parse(envVars);
    String parsedString = dbO.get("mongodb").toString();

    // Remove trailing and starting array brackets (otherwise it won't be valid JSON)
    parsedString = parsedString.replaceFirst("\\[ ", "");
    parsedString = parsedString.replaceFirst("\\]$", "");

    // Get the credentials
    dbO = (DBObject) JSON.parse(parsedString);
    parsedString = dbO.get("credentials").toString();

    // For debugging only
    // System.out.println(parsedString);

    dbO = (DBObject) JSON.parse(parsedString);

    System.out.println("Host name : " + dbO.get("hostname"));
    String hostName = dbO.get("hostname").toString();
    int port = Integer.parseInt(dbO.get("port").toString());
    String dbName = dbO.get("db").toString();
    String userName = dbO.get("username").toString();
    String password = dbO.get("password").toString();

    Mongo mongoClient = new Mongo(hostName, port);

    DB db = mongoClient.getDB(dbName);
    db.authenticate(userName, password.toCharArray());

    // Clean up old entries
    DBCollection coll = db.getCollection("testCollection");
    coll.drop();

    BasicDBObject lastAddedObject = null;
    for (String curItem : myGroceryList) {
        lastAddedObject = new BasicDBObject("i", curItem);
        coll.insert(lastAddedObject);
    }
    response.getWriter().println("<b>My grocery list is:</b>");

    coll.remove(lastAddedObject);
    DBCollection loadedCollection = db.getCollection("testCollection");
    DBCursor cursor = loadedCollection.find();
    try {
        response.getWriter().println("<ul>");
        while (cursor.hasNext()) {
            response.getWriter().println("<li>" + cursor.next().get("i") + "</li>");
        }
        response.getWriter().println("</ul>");
    } finally {
        cursor.close();
    }
}

From source file:com.sanaldiyar.projects.nanohttpd.mongodbbasedsessionhandler.MongoDBBasedSessionHandler.java

/**
 * Initilize secure random generator/*from w w w.j av  a2 s.com*/
 *
 * @param properties configuration
 */
public MongoDBBasedSessionHandler(Properties properties) {
    SecureRandom sr = new SecureRandom();
    srng = new SecureRandom(sr.generateSeed(16));

    String mdbbasedsh_host = properties.getProperty("mdbbasedsh.host");
    int mdbbasedsh_port = Integer.parseInt(properties.getProperty("mdbbasedsh.port"));
    String mdbbasedsh_database = properties.getProperty("mdbbasedsh.database");
    String mdbbasedsh_user = properties.getProperty("mdbbasedsh.user");
    String mdbbasedsh_password = properties.getProperty("mdbbasedsh.password");
    boolean flush = Boolean.parseBoolean(properties.getProperty("mdbbasedsh.flush"));

    mdbbasedsh_sesstimeout = Integer.parseInt(properties.getProperty("mdbbasedsh.sesstimeout"));

    try {
        mongoClient = new MongoClient(mdbbasedsh_host, mdbbasedsh_port);
        managers = mongoClient.getDB(mdbbasedsh_database);
        managers.authenticate(mdbbasedsh_user, mdbbasedsh_password.toCharArray());
        DBCollection sessions = managers.getCollection("sessions");
        if (flush) {
            sessions.drop();
            sessions = managers.getCollection("sessions");
        }
        sessions.ensureIndex(new BasicDBObject("sessionid", 1), "sessionid_idx", true);
        sessions.ensureIndex(new BasicDBObject("expires", 1));
    } catch (UnknownHostException ex) {
    }
}

From source file:com.socialsky.mods.MongoPersistor.java

License:Apache License

private void dropCollection(Message<JsonObject> message) {

    JsonObject reply = new JsonObject();
    String collection = getMandatoryString("collection", message);

    if (collection == null) {
        return;//from w w  w  . j a  v a 2 s .c  o  m
    }

    DBCollection coll = db.getCollection(collection);

    try {
        coll.drop();
        sendOK(message, reply);
    } catch (MongoException mongoException) {
        sendError(message, "exception thrown when attempting to drop collection: " + collection + " \n"
                + mongoException.getMessage());
    }
}

From source file:com.softinstigate.restheart.db.CollectionDAO.java

License:Open Source License

/**
 * Deletes a collection./*from w  ww. java  2  s. c om*/
 *
 * @param dbName the database name of the collection
 * @param collName the collection name
 * @param etag the entity tag. must match to allow actual write (otherwise
 * http error code is returned)
 * @return the HttpStatus code to set in the http response
 */
public static int deleteCollection(String dbName, String collName, ObjectId etag) {
    DBCollection coll = getCollection(dbName, collName);

    BasicDBObject checkEtag = new BasicDBObject("_id", "_properties");
    checkEtag.append("_etag", etag);

    DBObject exists = coll.findOne(checkEtag, fieldsToReturn);

    if (exists == null) {
        return HttpStatus.SC_PRECONDITION_FAILED;
    } else {
        coll.drop();
        return HttpStatus.SC_NO_CONTENT;
    }
}

From source file:com.uquetignyadminapp.connection.ConnectionMongoDB.java

public void supprimerTable(String table) {
    DBCollection col = getRecordsOfSpecificCollection(table);
    DBCursor cursor = col.find();/*  w  w  w .  j ava  2 s . co  m*/
    while (cursor.hasNext()) {
        col.remove(cursor.next());
    }
    col.drop();

}

From source file:com.wordnik.system.mongodb.RestoreUtil.java

License:Open Source License

protected void restore(CollectionInfo info) {
    try {//from  w ww  .  j av  a2  s .  co m
        System.out.println("restoring collection " + info.getName());
        File[] files = new File(INPUT_DIR).listFiles();
        if (files != null) {
            List<File> filesToProcess = new ArrayList<File>();
            for (File file : files) {
                if (file.getName().startsWith(info.getName()) && file.getName().indexOf(".bson") > 0) {
                    filesToProcess.add(file);
                }
            }
            Collections.sort(filesToProcess, new FilenameComparator());
            if (DROP_EXISTING) {
                try {
                    System.out.println("Dropping collection " + info.getName());

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

                    DBCollection coll = db.getCollection(info.getName());
                    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 " + info.getName());
                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(info.getName(), count, System.currentTimeMillis() - startTime);
                            lastOutput = System.currentTimeMillis();
                        }
                    }
                } catch (java.io.EOFException e) {
                    break;
                } finally {
                    inputStream.close();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}