Example usage for com.mongodb.client MongoCollection drop

List of usage examples for com.mongodb.client MongoCollection drop

Introduction

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

Prototype

void drop();

Source Link

Document

Drops this collection from the Database.

Usage

From source file:org.jongo.use_native.NativeTestBase.java

License:Apache License

protected <T> com.mongodb.client.MongoCollection<T> createNativeCollection(String collectionName,
        Class<T> clazz) {/*  w w  w. jav  a2 s. c  om*/
    com.mongodb.client.MongoCollection<T> col = jongo.getCollection(collectionName, clazz);
    col.drop();
    return col;
}

From source file:org.jongo.use_native.NativeTestBase.java

License:Apache License

protected com.mongodb.client.MongoCollection<Bson> createNativeCollection(String collectionName) {
    com.mongodb.client.MongoCollection<Bson> col = jongo.getCollection(collectionName);
    col.drop();
    return col;//from  w ww .j av  a  2  s . c om
}

From source file:org.nuxeo.directory.mongodb.MongoDBDirectory.java

License:Apache License

@Override
public Session getSession() throws DirectoryException {

    SchemaManager schemaManager = Framework.getService(SchemaManager.class);
    Schema schema = schemaManager.getSchema(getSchema());
    if (schema == null) {
        throw new DirectoryException(getSchema() + " is not a registered schema");
    }/* w ww.  j a  va 2 s . c  o m*/
    schemaFieldMap = new LinkedHashMap<>();
    schema.getFields().forEach(f -> schemaFieldMap.put(f.getName().getLocalName(), f));

    MongoDBSession session = new MongoDBSession(this);
    addSession(session);

    // Initialize counters collection if autoincrement enabled
    if (descriptor.isAutoincrementIdField() && !session.hasCollection(countersCollectionName)) {
        Map<String, Object> seq = new HashMap<>();
        seq.put(MONGODB_ID, getName());
        seq.put(MONGODB_SEQ, 0L);
        session.getCollection(countersCollectionName).insertOne(MongoDBSerializationHelper.fieldMapToBson(seq));
    }

    if (!initialized) {
        String policy = descriptor.getCreateTablePolicy();
        MongoCollection collection = session.getCollection(getName());
        boolean dropCollection = false;
        boolean loadData = false;

        switch (policy) {
        case CREATE_TABLE_POLICY_ALWAYS:
            dropCollection = true;
            loadData = true;
            break;
        case CREATE_TABLE_POLICY_ON_MISSING_COLUMNS:
            if (session.hasCollection(getName())) {
                long totalEntries = collection.count();
                boolean missingColumns = schema.getFields().stream().map(f -> f.getName().getLocalName())
                        .anyMatch(fname -> collection.count(Filters.exists(fname, false)) == totalEntries);
                if (missingColumns) {
                    dropCollection = true;
                    loadData = true;
                }
            } else {
                loadData = true;
            }
            break;
        default:
            if (!session.hasCollection(getName())) {
                loadData = true;
            }
            break;
        }
        if (dropCollection) {
            collection.drop();
        }
        if (loadData) {
            loadData(schema, session);
        }
        initialized = true;
    }
    return session;
}

From source file:org.restheart.db.CollectionDAO.java

License:Open Source License

/**
 * Deletes a collection.//from   w  w  w  .jav a 2  s  .com
 *
 * @param dbName the database name of the collection
 * @param collName the collection name
 * @param requestEtag 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
 */
OperationResult deleteCollection(final String dbName, final String collName, final String requestEtag,
        final boolean checkEtag) {
    MongoDatabase mdb = client.getDatabase(dbName);
    MongoCollection<Document> mcoll = mdb.getCollection("_properties");

    if (checkEtag) {
        Document properties = mcoll.find(eq("_id", "_properties.".concat(collName)))
                .projection(FIELDS_TO_RETURN).first();

        if (properties != null) {
            Object oldEtag = properties.get("_etag");

            if (oldEtag != null) {
                if (requestEtag == null) {
                    return new OperationResult(HttpStatus.SC_CONFLICT, oldEtag);
                } else if (!Objects.equals(oldEtag.toString(), requestEtag)) {
                    return new OperationResult(HttpStatus.SC_PRECONDITION_FAILED, oldEtag);
                }
            }
        }
    }

    MongoCollection<Document> collToDelete = mdb.getCollection(collName);
    collToDelete.drop();
    mcoll.deleteOne(eq("_id", "_properties.".concat(collName)));
    return new OperationResult(HttpStatus.SC_NO_CONTENT);
}

From source file:rapture.lock.mongodb.MongoLockHandler2.java

License:Open Source License

@Override
public Boolean forceReleaseLock(String lockName) {
    MongoCollection<Document> coll = getLockCollection(lockName);
    if (coll != null) {
        coll.drop();
    }/*from www  . j  a v  a 2s.  c  o m*/
    return true;
}

From source file:rapture.series.mongo.MongoSeriesStore.java

License:Open Source License

@Override
public void drop() {
    MongoCollection<Document> collection = getCollection(null);
    collection.drop();
    keyCache.invalidateAll();
}

From source file:rmteles.learning.mongodb.examples.week2.spark.HelloWorldMongoDBSparkFreemarkerStyle.java

License:Apache License

public static void main(String[] args) {
    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(HelloWorldMongoDBSparkFreemarkerStyle.class, "/freemarker");

    MongoClient client = new MongoClient(new ServerAddress("localhost", 27017));

    MongoDatabase database = client.getDatabase("course");
    final MongoCollection<Document> collection = database.getCollection("hello");
    collection.drop();

    collection.insertOne(new Document("name", "MongoDB"));

    Spark.get("/", (request, response) -> {
        StringWriter writer = new StringWriter();
        try {/*from www . j a  v  a  2s . c om*/
            Template helloTemplate = configuration.getTemplate("hello.ftl");

            Document document = collection.find().first();

            helloTemplate.process(document, writer);
        } catch (Exception e) {
            Spark.halt(500);
            e.printStackTrace();
        }
        return writer;
    });
}

From source file:tour.ClientSideEncryptionAutoEncryptionSettingsTour.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * Requires the mongodb-crypt library in the class path and mongocryptd on the system path.
 *
 * @param args ignored args//from w  w w. j av a  2  s  . c o m
 */
public static void main(final String[] args) {

    // This would have to be the same master key as was used to create the encryption key
    final byte[] localMasterKey = new byte[96];
    new SecureRandom().nextBytes(localMasterKey);

    Map<String, Map<String, Object>> kmsProviders = new HashMap<String, Map<String, Object>>() {
        {
            put("local", new HashMap<String, Object>() {
                {
                    put("key", localMasterKey);
                }
            });
        }
    };

    String keyVaultNamespace = "admin.datakeys";
    ClientEncryptionSettings clientEncryptionSettings = ClientEncryptionSettings.builder()
            .keyVaultMongoClientSettings(MongoClientSettings.builder()
                    .applyConnectionString(new ConnectionString("mongodb://localhost")).build())
            .keyVaultNamespace(keyVaultNamespace).kmsProviders(kmsProviders).build();

    ClientEncryption clientEncryption = ClientEncryptions.create(clientEncryptionSettings);
    BsonBinary dataKeyId = clientEncryption.createDataKey("local", new DataKeyOptions());
    final String base64DataKeyId = Base64.getEncoder().encodeToString(dataKeyId.getData());

    final String dbName = "test";
    final String collName = "coll";
    AutoEncryptionSettings autoEncryptionSettings = AutoEncryptionSettings.builder()
            .keyVaultNamespace(keyVaultNamespace).kmsProviders(kmsProviders)
            .schemaMap(new HashMap<String, BsonDocument>() {
                {
                    put(dbName + "." + collName,
                            // Need a schema that references the new data key
                            BsonDocument.parse("{" + "  properties: {" + "    encryptedField: {"
                                    + "      encrypt: {" + "        keyId: [{" + "          \"$binary\": {"
                                    + "            \"base64\": \"" + base64DataKeyId + "\","
                                    + "            \"subType\": \"04\"" + "          }" + "        }],"
                                    + "        bsonType: \"string\","
                                    + "        algorithm: \"AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic\""
                                    + "      }" + "    }" + "  }," + "  \"bsonType\": \"object\"" + "}"));
                }
            }).build();

    MongoClientSettings clientSettings = MongoClientSettings.builder()
            .autoEncryptionSettings(autoEncryptionSettings).build();

    MongoClient mongoClient = MongoClients.create(clientSettings);
    MongoCollection<Document> collection = mongoClient.getDatabase("test").getCollection("coll");
    collection.drop(); // Clear old data

    collection.insertOne(new Document("encryptedField", "123456789"));

    System.out.println(collection.find().first().toJson());

    // release resources
    mongoClient.close();
}

From source file:tour.ClientSideEncryptionSimpleTour.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * Requires the mongodb-crypt library in the class path and mongocryptd on the system path.
 * Assumes the schema has already been created in MongoDB.
 *
 * @param args ignored args//from  www.ja va 2s .  c om
 */
public static void main(final String[] args) {

    // This would have to be the same master key as was used to create the encryption key
    final byte[] localMasterKey = new byte[96];
    new SecureRandom().nextBytes(localMasterKey);

    Map<String, Map<String, Object>> kmsProviders = new HashMap<String, Map<String, Object>>() {
        {
            put("local", new HashMap<String, Object>() {
                {
                    put("key", localMasterKey);
                }
            });
        }
    };

    String keyVaultNamespace = "admin.datakeys";

    AutoEncryptionSettings autoEncryptionSettings = AutoEncryptionSettings.builder()
            .keyVaultNamespace(keyVaultNamespace).kmsProviders(kmsProviders).build();

    MongoClientSettings clientSettings = MongoClientSettings.builder()
            .autoEncryptionSettings(autoEncryptionSettings).build();

    MongoClient mongoClient = MongoClients.create(clientSettings);
    MongoCollection<Document> collection = mongoClient.getDatabase("test").getCollection("coll");
    collection.drop(); // Clear old data

    collection.insertOne(new Document("encryptedField", "123456789"));

    System.out.println(collection.find().first().toJson());

    // release resources
    mongoClient.close();
}

From source file:tour.Decimal128QuickTour.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes an optional single argument for the connection string
 *//*from www  .  j a  v  a 2  s.  c o m*/
public static void main(final String[] args) {
    MongoClient mongoClient;

    if (args.length == 0) {
        // connect to the local database server
        mongoClient = new MongoClient();
    } else {
        mongoClient = new MongoClient(new MongoClientURI(args[0]));
    }

    // get handle to "mydb" database
    MongoDatabase database = mongoClient.getDatabase("mydb");

    // get a handle to the "test" collection
    MongoCollection<Document> collection = database.getCollection("test");

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

    // make a document and insert it
    Document doc = new Document("name", "MongoDB").append("amount1", Decimal128.parse(".10"))
            .append("amount2", new Decimal128(42L)).append("amount3", new Decimal128(new BigDecimal(".200")));

    collection.insertOne(doc);

    Document first = collection.find().filter(Filters.eq("amount1", new Decimal128(new BigDecimal(".10"))))
            .first();

    Decimal128 amount3 = (Decimal128) first.get("amount3");
    BigDecimal amount2AsBigDecimal = amount3.bigDecimalValue();

    System.out.println(amount3.toString());
    System.out.println(amount2AsBigDecimal.toString());

}