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:JavaSimpleExample.java

License:MIT License

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

    // Create seed data

    final BasicDBObject[] seedData = createSeedData();

    // Standard URI format: mongodb://[dbuser:dbpassword@]host:port/dbname

    MongoClientURI uri = new MongoClientURI("mongodb://user:pass@host:port/db");
    MongoClient client = new MongoClient(uri);
    DB db = client.getDB(uri.getDatabase());

    /*//from  w ww .  j  a  v a 2s. co  m
     * First we'll add a few songs. Nothing is required to create the
     * songs collection; it is created automatically when we insert.
     */

    DBCollection songs = db.getCollection("songs");

    // Note that the insert method can take either an array or a document.

    songs.insert(seedData);

    /*
     * Then we need to give Boyz II Men credit for their contribution to
     * the hit "One Sweet Day".
     */

    BasicDBObject updateQuery = new BasicDBObject("song", "One Sweet Day");
    songs.update(updateQuery,
            new BasicDBObject("$set", new BasicDBObject("artist", "Mariah Carey ft. Boyz II Men")));

    /*
     * Finally we run a query which returns all the hits that spent 10 
     * or more weeks at number 1.
     */

    BasicDBObject findQuery = new BasicDBObject("weeksAtOne", new BasicDBObject("$gte", 10));
    BasicDBObject orderBy = new BasicDBObject("decade", 1);

    DBCursor docs = songs.find(findQuery).sort(orderBy);

    while (docs.hasNext()) {
        DBObject doc = docs.next();
        System.out.println("In the " + doc.get("decade") + ", " + doc.get("song") + " by " + doc.get("artist")
                + " topped the charts for " + doc.get("weeksAtOne") + " straight weeks.");
    }

    // Since this is an example, we'll clean up after ourselves.

    songs.drop();

    // Only close the connection when your app is terminating

    client.close();
}

From source file:bruma.tools.Isis2Mongo.java

License:Open Source License

public static void main(final String[] args) {
    if (args.length < 3) {
        usage();/*from w  ww .  j  a  v a 2 s . c o m*/
    }

    String isisMaster = null;
    String mongoDbName = null;
    String mongoCollection = null;
    String host = "localhost";
    int port = DEFAULT_PORT;
    String user = null;
    String password = null;
    String encoding = Master.GUESS_ISO_IBM_ENCODING;
    int from = 1;
    int to = Integer.MAX_VALUE;
    int idTag = 0;
    int tell = Integer.MAX_VALUE;
    boolean useFDT = false;
    boolean useOnlyFDT = false;
    boolean clearCollection = false;

    for (String arg : args) {
        if (arg.startsWith("-isisMaster=")) {
            isisMaster = arg.substring(12);
        } else if (arg.startsWith("-mongoDbName=")) {
            mongoDbName = arg.substring(13);
        } else if (arg.startsWith("-collection=")) {
            mongoCollection = arg.substring(12);
        } else if (arg.startsWith("-mongoHost=")) {
            host = arg.substring(11);
        } else if (arg.startsWith("-mongoPort=")) {
            port = Integer.parseInt(arg.substring(11));
        } else if (arg.startsWith("-user=")) {
            user = arg.substring(6);
        } else if (arg.startsWith("-password=")) {
            password = arg.substring(10);
        } else if (arg.startsWith("-encod=")) {
            encoding = arg.substring(7);
        } else if (arg.startsWith("-from=")) {
            from = Integer.parseInt(arg.substring(6));
        } else if (arg.startsWith("-to=")) {
            to = Integer.parseInt(arg.substring(4));
        } else if (arg.startsWith("-idTag=")) {
            idTag = Integer.parseInt(arg.substring(7));
        } else if (arg.startsWith("-tell=")) {
            tell = Integer.parseInt(arg.substring(6));
        } else if (arg.equals("--useFDT")) {
            useFDT = true;
        } else if (arg.equals("--useOnlyFDT")) {
            useOnlyFDT = true;
        } else if (arg.equals("--clearCollection")) {
            clearCollection = true;
        } else {
            usage();
        }
    }

    final Logger log = Logger.getLogger("Isis2Mongo");
    final List<DBObject> buffer = new ArrayList<DBObject>();

    try {
        final DB database = getDatabase(host, port, user, password, mongoDbName);
        final DBCollection collection = database.getCollection(mongoCollection);
        final Master mst = MasterFactory.getInstance(isisMaster).setEncoding(encoding).open();
        final boolean hasFdt = new File(Util.changeFileExtension(isisMaster, ZeFDT.DEFAULT_EXTENSION)).isFile();
        final ZeFDT fdt = ((useFDT || useOnlyFDT) && hasFdt) ? new ZeFDT().fromFile(isisMaster) : null;
        final Map<Integer, ZeFDT.ZeFDTField> mfdt = (fdt == null) ? null : fdt.getFieldDescriptionMapEx();

        to = Math.min(to, mst.getControlRecord().getNxtmfn() - 1);
        int cur = 0;

        if (clearCollection) {
            collection.drop();
        }

        for (int mfn = from; mfn <= to; mfn++) {
            final Record rec = mst.getRecord(mfn);

            if (rec.getStatus() == Record.Status.ACTIVE) {
                buffer.add(createDocument(rec, idTag, mfdt, useOnlyFDT));
                if (buffer.size() == DEFAULT_BUFFER_SIZE) {
                    final String errMess = collection.insert(buffer).getError();
                    if (errMess != null) {
                        log.warning(errMess);
                    }
                    buffer.clear();
                }
            }

            if (++cur == tell) {
                cur = 0;
                log.info("+++ " + Integer.toString(mfn));
            }
        }
        if (!buffer.isEmpty()) {
            final String errMess = collection.insert(buffer).getError();
            if (errMess != null) {
                log.warning(errMess);
            }
        }

        mst.close();
        log.info("Importing ");
        log.info(args[0]);
        log.info(" finished.");
        log.info("Documents imported: ");
        log.info(Integer.toString(cur));
        log.info("Total documents : ");
        log.info(Long.toString(collection.count()));
    } catch (Exception ex) {
        log.severe(ex.getMessage());
    }
}

From source file:com.andreig.jetty.CollectionsServlet.java

License:GNU General Public License

@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.fine("doDelete()");

    if (!can_admin(req)) {
        res.sendError(SC_UNAUTHORIZED);/* w  w w . j ava2s . co  m*/
        return;
    }

    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    if (db_name == null || col_name == null) {
        String names[] = req2mongonames(req);
        if (names != null) {
            db_name = names[0];
            col_name = names[1];
        }
        if (db_name == null || col_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }
    }

    DB db = mongo.getDB(db_name);
    DBCollection col = db.getCollection(col_name);
    col.drop();
    res.setStatus(SC_OK);

}

From source file:com.caci.dummyserver.MongoRepository.java

public void clear(String table) {
    DB db = mongo.getDB("Objects");
    DBCollection col = db.getCollection(table);
    col.drop();
}

From source file:com.cyslab.craftvm.rest.mongo.CollectionsServlet.java

License:GNU General Public License

@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.trace("doDelete()");

    if (!can_admin(req)) {
        res.sendError(SC_UNAUTHORIZED);//from w w w .j a  va  2 s . c o  m
        return;
    }

    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    if (db_name == null || col_name == null) {
        String names[] = req2mongonames(req);
        if (names != null) {
            db_name = names[0];
            col_name = names[1];
        }
        if (db_name == null || col_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }
    }

    DB db = mongo.getDB(db_name);
    DBCollection col = db.getCollection(col_name);
    col.drop();
    res.setStatus(SC_OK);

}

From source file:com.ebay.cloud.cms.entmgr.branch.impl.BranchServiceImpl.java

License:Apache License

@Override
public void deleteMetadata(String repoName, MetaClass metadata, EntityContext context) {
    // drop all metadata related collection for each branch
    Repository repo = this.repositoryService.getRepository(repoName);
    List<IBranch> branches = getMainBranches(repoName, context);
    for (IBranch b : branches) {
        PersistenceContext persistenceContext = PersistenceContextFactory.createEntityPersistenceConext(
                repo.getMetadataService(), b.getId(), context.getConsistentPolicy(), context.getRegistration(),
                context.isFetchFieldProperty(), context.getDbConfig(), context.getAdditionalCriteria());
        persistenceContext.setMongoDataSource(ds);
        DBCollection coll = persistenceContext.getDBCollection(metadata);
        coll.drop();
    }/*from w  w  w  .  j  a  v  a 2  s  . c  o m*/
}

From source file:com.ebay.cloud.cms.entmgr.loader.RuntimeDataLoader.java

License:Apache License

/**
 * clean up two collections: main and branches
 * FIXME: for testing purpose, we can only load entities from main branch
 *//* w  w  w.j  a  va 2 s.  c  o m*/
public void cleanUp() {
    //main collection pattern: rootbranchid_metaclassname
    //sub branch collection pattern: rootbranchid_subs_metaclassname
    //history collection pattern: rootbranchid_metaclassname_history

    //TODO: find a way to clean up runtime  collections

    logger.debug(String.format("To clean up all runtime data in repository %s", repositoryName));
    //drop main repository
    DB db = dataSource.getMongoInstance().getDB(repositoryName);

    Set<String> allColNames = db.getCollectionNames();
    for (String colName : allColNames) {
        if (isRuntimeCollection(colName)) {
            DBCollection dbCollection = db.getCollection(colName);
            dbCollection.drop();
        } else {
            logger.debug("don't drop collection " + colName);
        }
    }

    BranchServiceImpl bimpl = (BranchServiceImpl) branchService;
    bimpl.clearBranchCache();
}

From source file:com.ebay.cloud.cms.metadata.dataloader.MetadataDataLoader.java

License:Apache License

public void cleanDatabase(String dbName) {
    DB db = mongo.getDB(dbName);/*from   w w w .j  av a2s .c  o  m*/
    Set<String> allColNames = db.getCollectionNames();
    for (String colName : allColNames) {
        if (isSystemClollection(colName)) {
            logger.info("don't drop collection {}", colName);
        } else {
            DBCollection dbCollection = db.getCollection(colName);
            dbCollection.drop();
        }
    }
}

From source file:com.edduarte.argus.Context.java

License:Apache License

/**
 * Removes existing differences for the specified url
 */// w  w w.j ava2 s  . c  om
@Override
public void removeExistingDifferences(String url) {
    DBCollection diffColl = differencesDB.getCollection(url);
    diffColl.drop();
}

From source file:com.edduarte.argus.document.DocumentCollection.java

License:Apache License

public void destroy() {
    DBCollection collection = documentsDB.getCollection(collectionName);
    collection.drop();
    documentsCache.destroy();//from w w  w.  ja va  2 s  .co m
    documentsDB.dropDatabase();
    occurrencesDB.dropDatabase();
}