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:org.apache.hadoop.contrib.mongoreduce.MongoStreamOutputFormat.java

License:Apache License

public void checkOutputSpecs(FileSystem ignored, JobConf conf) throws IOException {

    if (conf.getBoolean("mongo.output.skip_splitting", false))
        return;/*from ww w  .j a v  a  2s  . co  m*/

    String database = conf.get("mongo.output.database", "");
    if (database.equals("")) {
        throw new IOException("must specify a value for mongo.output.database");
    }

    String collection = conf.get("mongo.output.collection", "");
    if (collection.equals("")) {
        throw new IOException("must supply a value for mongo.output.collection");
    }

    // connect to global db
    Mongo m = new Mongo("localhost");
    DB db = m.getDB(database);
    DB admindb = m.getDB("admin");
    DB configdb = m.getDB("config");

    // optionally drop the existing collection
    boolean drop = conf.getBoolean("mongo.output.drop", false);
    DBCollection coll = db.getCollection(collection);
    if (drop) {
        coll.drop();
    } else {
        if (coll.count() > 0) {
            // don't shard an existing collection - may already be sharded ...
            return;
        }
    }

    // get a list of shards
    ArrayList<String> shards = new ArrayList<String>();
    for (DBObject s : configdb.getCollection("shards").find()) {
        shards.add((String) s.get("_id"));
    }

    if (shards.size() < 2) {
        // don't let's be silly
        return;
    }

    // shard the new output collection
    BasicDBObjectBuilder builder = new BasicDBObjectBuilder();
    builder.add("enableSharding", database);
    admindb.command(builder.get());

    builder = new BasicDBObjectBuilder();
    builder.add("shardCollection", database + "." + collection);

    // just shard on _id - but user gets to decide what the _id is
    builder.add("key", new BasicDBObject("_id", 1));
    admindb.command(builder.get());

    // pre-split to get parallel writes
    // this http://www.mongodb.org/display/DOCS/Splitting+Chunks says 
    // balancer moving chunks should take 5 minutes ... too long
    // wonder if moveChunk command is faster
    // well we could do it anyway - the jobs that can benefit from it will

    // check for user-submitted splitPoints
    String[] splits;
    String splitString = conf.get("mongo.output.split_points", "");

    // generate our own split points if necessary
    if (splitString.equals("")) {
        long max = (long) Math.pow(93.0, 5.0);

        long step = max / shards.size();
        splits = new String[shards.size() - 1];

        // assume human readable keys
        for (int i = 0; i < shards.size() - 1; i++) {
            splits[i] = splitPointForLong(step * (i + 1));
        }
    } else {
        splits = splitString.split(",");
    }

    HashMap<String, Object> splitCmd = new HashMap<String, Object>();
    splitCmd.put("split", database + "." + collection);
    splitCmd.put("middle", "");

    HashMap<String, Object> moveCmd = new HashMap<String, Object>();
    moveCmd.put("moveChunk", database + "." + collection);
    moveCmd.put("find", "");
    moveCmd.put("to", "");

    // do the splitting and migrating
    // we assign chunks to shards in a round-robin manner
    int i = 0;
    for (String split : splits) {

        splitCmd.remove("middle");
        splitCmd.put("middle", new BasicDBObject("_id", split));

        // create new chunk
        admindb.command(new BasicDBObject(splitCmd));

        // move to shard
        moveCmd.remove("find");
        moveCmd.put("find", new BasicDBObject("_id", split));
        moveCmd.put("to", shards.get(i));

        admindb.command(new BasicDBObject(moveCmd));

        i = (i + 1) % shards.size();
    }
}

From source file:org.apache.metamodel.mongodb.mongo2.MongoDbUpdateCallback.java

License:Apache License

protected void removeCollection(String name) {
    DBCollection collection = getCollection(name);
    _collections.remove(name);
    collection.drop();
}

From source file:org.aw20.mongoworkbench.command.CreateDbsMongoCommand.java

License:Open Source License

@Override
public void execute() throws Exception {
    MongoClient mdb = MongoFactory.getInst().getMongo(sName);

    if (mdb == null)
        throw new Exception("no server selected");

    DB db = mdb.getDB(sDb);/*  w w  w . java2s .c o m*/

    String colTemp = "tmp" + System.currentTimeMillis();
    DBCollection coll = db.createCollection(colTemp, new BasicDBObject());
    coll.drop();

    setDBNames(mdb);
}

From source file:org.aw20.mongoworkbench.command.DropCollectionMongoCommand.java

License:Open Source License

@Override
public void execute() throws Exception {
    MongoClient mdb = MongoFactory.getInst().getMongo(sName);
    if (mdb == null)
        throw new Exception("no server selected");

    if (sDb == null)
        throw new Exception("no database selected");

    MongoFactory.getInst().setActiveDB(sDb);

    DB db = mdb.getDB(sDb);/*from w  w w.j  a v  a2 s  .  c  o  m*/

    DBCollection collection = db.getCollection(sColl);
    collection.drop();

    super.execute();
}

From source file:org.benjp.services.mongodb.MongoBootstrap.java

License:Open Source License

private void dropTokenCollectionIfExists() {
    if (getDB().collectionExists("tokens")) {
        DBCollection tokens = getDB().getCollection("tokens");
        tokens.drop();
    }/*w w  w  . jav a2 s.c  o  m*/
}

From source file:org.breizhbeans.thrift.tools.thriftmongobridge.example.SimpleApp.java

License:Apache License

public static void main(String[] args) throws Exception {
    // ---------------------------------------------------------------
    // NON SECURED GET ALWAYS PASSWORD'S KEYSTORE FROM A SECURED PLACE
    // get it from a secured console
    String pwd = args[0];//  w w w . ja v a 2 s . co m
    // get it from a console
    String keyProtectedPassword = args[1];
    // NON SECURED GET ALWAYS PASSWORD'S KEYSTORE FROM A SECURED PLACE
    // ---------------------------------------------------------------

    // load key from the key store
    final KeyStore keyStore = KeyStore.getInstance("JCEKS");
    keyStore.load(new FileInputStream("./keystore/secretkey.keystore"), pwd.toCharArray());

    // Extract the AES key
    KeyStore.PasswordProtection keyPassword = new KeyStore.PasswordProtection(
            keyProtectedPassword.toCharArray());
    KeyStore.SecretKeyEntry aesKey = (KeyStore.SecretKeyEntry) keyStore.getEntry("aesKey", keyPassword);

    // AES KEY
    byte[] key = aesKey.getSecretKey().getEncoded();

    // Secured bridge initialisation
    // First create the wrapper
    SecuredWrapper securedWrapper = new SecuredWrapper(key);

    // Set the fields protected
    securedWrapper.secureThriftFields(People.class, true, People._Fields.FIRST_NAME);
    securedWrapper.secureThriftFields(People.class, true, People._Fields.LAST_NAME);
    securedWrapper.secureThriftFields(People.class, false, People._Fields.BIRTHDAY);
    securedWrapper.secureThriftFields(People.class, true, People._Fields.EMAIL);

    // Add the wrapper
    TBSONUnstackedProtocol.addSecuredWrapper(securedWrapper);

    // setup mongo
    // and get the collection
    MongoClient mongo = new MongoClient("localhost", 27017);
    DB db = mongo.getDB("example-thrift-mongo");
    DBCollection peoples = db.getCollection("people");

    // write people
    People people = new People();

    people.setFirstName("my secret first name");
    people.setLastName("my secret last name");
    people.setEmail("me@me");
    people.setInceptionDate(System.currentTimeMillis());
    people.setBirthday("1970-01-01");
    people.setLanguage("en");

    // serialize it
    DBObject dbObject = ThriftMongoHelper.thrift2DBObject(people);

    System.out.println("save=" + dbObject.toString());

    // write the document
    peoples.save(dbObject);

    // find document by secured field
    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put(People._Fields.FIRST_NAME.getFieldName(),
            securedWrapper.digest64("my secret first name".getBytes()));

    System.out.println("query=" + searchQuery.toString());

    DBCursor cursor = peoples.find(searchQuery);

    while (cursor.hasNext()) {
        // print secured people
        DBObject dbSecuredObject = cursor.next();
        System.out.println("secured=" + dbSecuredObject);

        // deserialize the secured object
        People peopleDeserialized = (People) ThriftMongoHelper.DBObject2Thrift(dbSecuredObject, People.class);
        System.out.println("unwrapped=" + peopleDeserialized.toString());
    }

    // Bye
    System.out.println("Thrift and mongo rocks :D");
    System.out.println("Destroy the collection");
    peoples.drop();
}

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

License:Apache License

public void dropCollection(ServerConfiguration configuration, MongoCollection mongoCollection) {
    MongoClient mongo = null;//from  w  w  w . java2s . c om
    try {
        String databaseName = mongoCollection.getDatabaseName();
        mongo = createMongoClient(configuration);

        DB database = mongo.getDB(databaseName);
        DBCollection collection = database.getCollection(mongoCollection.getName());

        collection.drop();
    } catch (UnknownHostException ex) {
        throw new ConfigurationException(ex);
    } finally {
        if (mongo != null) {
            mongo.close();
        }
    }
}

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

License:Apache License

public void dropCollection(ServerConfiguration configuration, MongoCollection mongoCollection) {
    com.mongodb.MongoClient mongo = null;
    try {/*from w w w.j a va2  s.co  m*/
        String databaseName = mongoCollection.getDatabaseName();
        mongo = createMongoClient(configuration);

        DB database = mongo.getDB(databaseName);
        DBCollection collection = database.getCollection(mongoCollection.getName());

        collection.drop();
    } catch (UnknownHostException ex) {
        throw new ConfigurationException(ex);
    } finally {
        if (mongo != null) {
            mongo.close();
        }
    }
}

From source file:org.datanucleus.store.mongodb.MongoDBSchemaHandler.java

License:Open Source License

@Override
public void deleteSchemaForClasses(Set<String> classNames, Properties props, Object connection) {
    DB db = (DB) connection;/*from w  w w .jav  a 2  s .  com*/
    ManagedConnection mconn = null;
    try {
        if (db == null) {
            mconn = storeMgr.getConnection(-1);
            db = (DB) mconn.getConnection();
        }

        Iterator<String> classIter = classNames.iterator();
        ClassLoaderResolver clr = storeMgr.getNucleusContext().getClassLoaderResolver(null);
        while (classIter.hasNext()) {
            String className = classIter.next();
            AbstractClassMetaData cmd = storeMgr.getMetaDataManager().getMetaDataForClass(className, clr);
            if (cmd != null) {
                StoreData storeData = storeMgr.getStoreDataForClass(cmd.getFullClassName());
                Table table = null;
                if (storeData != null) {
                    table = storeData.getTable();
                } else {
                    table = new CompleteClassTable(storeMgr, cmd, null);
                }
                DBCollection collection = db.getCollection(table.getName());
                collection.dropIndexes();
                if (NucleusLogger.DATASTORE_SCHEMA.isDebugEnabled()) {
                    NucleusLogger.DATASTORE_SCHEMA.debug(Localiser.msg("MongoDB.SchemaDelete.Class",
                            cmd.getFullClassName(), table.getName()));
                }
                collection.drop();
            }
        }
    } finally {
        if (mconn != null) {
            mconn.release();
        }
    }
}

From source file:org.datanucleus.store.mongodb.MongoDBStoreManager.java

License:Open Source License

public void deleteSchema(Set<String> classNames, Properties props) {
    ManagedConnection mconn = getConnection(-1);
    try {//from w w  w . j  a  va2s .c  o m
        DB db = (DB) mconn.getConnection();

        Iterator<String> classIter = classNames.iterator();
        ClassLoaderResolver clr = nucleusContext.getClassLoaderResolver(null);
        while (classIter.hasNext()) {
            String className = classIter.next();
            AbstractClassMetaData cmd = getMetaDataManager().getMetaDataForClass(className, clr);
            if (cmd != null) {
                DBCollection collection = db.getCollection(getNamingFactory().getTableName(cmd));
                collection.dropIndexes();
                collection.drop();
            }
        }
    } finally {
        mconn.release();
    }
}