Example usage for com.mongodb.client MongoDatabase createCollection

List of usage examples for com.mongodb.client MongoDatabase createCollection

Introduction

In this page you can find the example usage for com.mongodb.client MongoDatabase createCollection.

Prototype

void createCollection(ClientSession clientSession, String collectionName);

Source Link

Document

Create a new collection with the given name.

Usage

From source file:com.imaginea.mongodb.services.impl.CollectionServiceImpl.java

License:Apache License

/**
 * Deletes a collection inside a database in mongo to which user is connected to.
 *
 * @param dbName Name of Database in which to insert a collection
 * @param collectionName Name of Collection to be inserted
 * @return Success if deletion is successful else throw exception
 * @throws DatabaseException throw super type of UndefinedDatabaseException
 * @throws ValidationException throw super type of
 *         EmptyDatabaseNameException,EmptyCollectionNameException
 * @throws CollectionException throw super type of
 *         UndefinedCollectionException,DeleteCollectionException
 *//*from  w  w w .  jav a 2s . com*/

private void createCollection(CreateCollectionOptions options, MongoCollection<Document> selectedCollection,
        String selectedCollectionName, MongoDatabase db) {
    db.createCollection(selectedCollectionName + "_temp", options);
    MongoCollection<Document> tempCollection = db.getCollection(selectedCollectionName + "_temp");

    MongoCursor<Document> cur = selectedCollection.find().iterator();
    while (cur.hasNext()) {
        Document obj = cur.next();
        tempCollection.insertOne(obj);
    }
    MongoNamespace namespace = selectedCollection.getNamespace();
    selectedCollection.drop();
    tempCollection.renameCollection(namespace);
}

From source file:com.telefonica.iot.cygnus.backends.mongo.MongoBackendImpl.java

License:Open Source License

/**
 * Creates a collection for plain MongoDB, given its name, if not exists in the given database. Size-based limits
 * are set, if possible. Time-based limits are also set, if possible.
 * @param dbName//  w w  w .j  a  v  a2s  .c o m
 * @param collectionName
 * @param collectionsSize
 * @param maxDocuments
 * @throws Exception
 */
@Override
public void createCollection(String dbName, String collectionName, long collectionsSize, long maxDocuments,
        long dataExpiration) throws Exception {
    MongoDatabase db = getDatabase(dbName);

    // create the collection, with size-based limits if possible
    try {
        if (collectionsSize != 0 && maxDocuments != 0) {
            CreateCollectionOptions options = new CreateCollectionOptions().capped(true)
                    .sizeInBytes(collectionsSize).maxDocuments(maxDocuments);
            LOGGER.debug("Creating Mongo collection=" + collectionName + " at database=" + dbName + " with "
                    + "collections_size=" + collectionsSize + " and max_documents=" + maxDocuments
                    + " options");
            db.createCollection(collectionName, options);
        } else {
            LOGGER.debug("Creating Mongo collection=" + collectionName + " at database=" + dbName);
            db.createCollection(collectionName);
        } // if else
    } catch (Exception e) {
        if (e.getMessage().contains("collection already exists")) {
            LOGGER.debug("Collection already exists, nothing to create");
        } else {
            throw e;
        } // if else
    } // try catch

    // ensure the recvTime index, if possible
    try {
        if (dataExpiration != 0) {
            BasicDBObject keys = new BasicDBObject().append("recvTime", 1);
            IndexOptions options = new IndexOptions().expireAfter(dataExpiration, TimeUnit.SECONDS);
            db.getCollection(collectionName).createIndex(keys, options);
        } // if
    } catch (Exception e) {
        throw e;
    } // try catch
}

From source file:io.mandrel.common.mongo.MongoUtils.java

License:Apache License

public static void checkCapped(MongoDatabase database, String collectionName, int size, int maxDocuments) {
    if (Lists.newArrayList(database.listCollectionNames()).contains(collectionName)) {
        log.debug("'{}' collection already exists...", collectionName);

        // Check if already capped
        Document command = new Document("collStats", collectionName);
        boolean isCapped = database.runCommand(command, ReadPreference.primary()).getBoolean("capped")
                .booleanValue();/* www .j a va2  s .  com*/

        if (!isCapped) {
            log.info("'{}' is not capped, converting it...", collectionName);
            command = new Document("convertToCapped", collectionName).append("size", size).append("max",
                    maxDocuments);
            database.runCommand(command, ReadPreference.primary());
        } else {
            log.debug("'{}' collection already capped!", collectionName);
        }

    } else {
        database.createCollection(collectionName,
                new CreateCollectionOptions().capped(true).maxDocuments(maxDocuments).sizeInBytes(size));
    }
}

From source file:mongodb.QuickTourAdmin.java

License:Apache License

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

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

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

    database.drop();

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

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

    // getting a list of databases
    for (String name : mongoClient.listDatabaseNames()) {
        System.out.println(name);
    }

    // drop a database
    mongoClient.getDatabase("databaseToBeDropped").drop();

    // create a collection
    database.createCollection("cappedCollection",
            new CreateCollectionOptions().capped(true).sizeInBytes(0x100000));

    for (String name : database.listCollectionNames()) {
        System.out.println(name);
    }

    // drop a collection:
    collection.drop();

    // create an ascending index on the "i" field
    // 1 ascending or -1 for descending
    collection.createIndex(new Document("i", 1));

    // list the indexes on the collection
    for (final Document index : collection.listIndexes()) {
        System.out.println(index.toJson());
    }

    // create a text index on the "content" field
    // text indexes to support text search of string content
    collection.createIndex(new Document("content", "text"));

    collection.insertOne(new Document("_id", 0).append("content", "textual content"));
    collection.insertOne(new Document("_id", 1).append("content", "additional content"));
    collection.insertOne(new Document("_id", 2).append("content", "irrelevant content"));

    // Find using the text index
    long matchCount = collection.count(text("textual content -irrelevant"));
    System.out.println("Text search matches: " + matchCount);

    // Find using the $language operator
    Bson textSearch = text("textual content -irrelevant", "english");
    matchCount = collection.count(textSearch);
    System.out.println("Text search matches (english): " + matchCount);

    // Find the highest scoring match
    Document projection = new Document("score", new Document("$meta", "textScore"));
    Document myDoc = collection.find(textSearch).projection(projection).first();
    System.out.println("Highest scoring document: " + myDoc.toJson());

    // Run a command
    Document buildInfo = database.runCommand(new Document("buildInfo", 1));
    System.out.println(buildInfo);

    // release resources
    database.drop();
    mongoClient.close();
}

From source file:net.netzgut.integral.mongo.internal.services.MongoServiceImplementation.java

License:Apache License

@Override
public void capCollection(MongoDatabase db, String collectionName, long sizeInBytes) {
    final MongoIterable<String> result = db.listCollectionNames();
    final List<String> names = result.into(new ArrayList<>());

    if (names.contains(collectionName)) {
        final Document getStats = new Document("collStats", collectionName);
        final Document stats = db.runCommand(getStats);
        Object capped = stats.get("capped");
        final boolean isCapped = capped != null && capped.equals(1);
        if (isCapped == false) {
            final Document convertToCapped = new Document();
            convertToCapped.append("convertToCapped", collectionName);
            convertToCapped.append("size", sizeInBytes);
            db.runCommand(convertToCapped);

            // We need to create the index manually after conversion.
            // See red warning box: http://docs.mongodb.org/v2.2/reference/command/convertToCapped/#dbcmd.convertToCapped
            db.getCollection(collectionName).createIndex(new Document("_id", 1));
        }/*from  w ww .jav a2s .c om*/
    } else {
        db.createCollection(collectionName,
                new CreateCollectionOptions().capped(true).sizeInBytes(sizeInBytes));
    }

}

From source file:org.bananaforscale.cormac.dao.collection.CollectionDataServiceImpl.java

License:Apache License

/**
 * Creates a new collection explicitly. Because MongoDB creates a collection
 * implicitly when the collection is first referenced in a command, this
 * method is not required for usage of said collection.
 *
 * @param databaseName the database/*from www  .j  a v  a2  s .c o  m*/
 * @param collectionName the collection to create
 * @return the result of the operation
 * @throws DatasourceException
 * @throws ExistsException
 * @throws NotFoundException
 */
@Override
public boolean addCollection(String databaseName, String collectionName)
        throws DatasourceException, ExistsException, NotFoundException {
    try {
        if (!databaseExists(databaseName)) {
            throw new NotFoundException("The database doesn't exist in the datasource");
        }
        if (collectionExists(databaseName, collectionName)) {
            throw new ExistsException("The collection already exists in the datasource");
        }
        MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);
        CreateCollectionOptions options = new CreateCollectionOptions();
        options.capped(false);
        mongoDatabase.createCollection(collectionName, options);
        return true;
    } catch (MongoException ex) {
        logger.error("An error occured while adding the collection", ex);
        throw new DatasourceException("An error occured while adding the collection");
    }
}

From source file:tour.NewQuickTour.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 w  w  w  .  j  ava2s.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");

    database.drop();

    // get a list of the collections in this database and print them out
    List<String> collectionNames = database.listCollectionNames().into(new ArrayList<String>());
    for (final String s : collectionNames) {
        System.out.println(s);
    }

    // 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("type", "database").append("count", 1).append("info",
            new Document("x", 203).append("y", 102));

    collection.insertOne(doc);

    // get it (since it's the only one in there since we dropped the rest earlier on)
    Document myDoc = collection.find().first();
    System.out.println(myDoc);

    // now, lets add lots of little documents to the collection so we can explore queries and cursors
    List<Document> documents = new ArrayList<Document>();
    for (int i = 0; i < 100; i++) {
        documents.add(new Document("i", i));
    }
    collection.insertMany(documents);
    System.out.println(
            "total # of documents after inserting 100 small ones (should be 101) " + collection.count());

    // lets get all the documents in the collection and print them out
    MongoCursor<Document> cursor = collection.find().iterator();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    for (Document cur : collection.find()) {
        System.out.println(cur);
    }

    // now use a query to get 1 document out
    myDoc = collection.find(eq("i", 71)).first();
    System.out.println(myDoc);

    // now use a range query to get a larger subset
    cursor = collection.find(gt("i", 50)).iterator();

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    // range query with multiple constraints
    cursor = collection.find(and(gt("i", 50), lte("i", 100))).iterator();

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    // max time
    collection.find().maxTime(1, TimeUnit.SECONDS).first();

    collection.drop();

    // ordered bulk writes
    List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>();
    writes.add(new InsertOneModel<Document>(new Document("_id", 4)));
    writes.add(new InsertOneModel<Document>(new Document("_id", 5)));
    writes.add(new InsertOneModel<Document>(new Document("_id", 6)));
    writes.add(
            new UpdateOneModel<Document>(new Document("_id", 1), new Document("$set", new Document("x", 2))));
    writes.add(new DeleteOneModel<Document>(new Document("_id", 2)));
    writes.add(new ReplaceOneModel<Document>(new Document("_id", 3), new Document("_id", 3).append("x", 4)));

    collection.bulkWrite(writes);

    collection.drop();

    collection.bulkWrite(writes, new BulkWriteOptions().ordered(false));

    // getting a list of databases
    for (String name : mongoClient.listDatabaseNames()) {
        System.out.println(name);
    }

    // drop a database
    mongoClient.dropDatabase("databaseToBeDropped");

    // create a collection
    database.createCollection("cappedCollection",
            new CreateCollectionOptions().capped(true).sizeInBytes(0x100000));

    for (String name : database.listCollectionNames()) {
        System.out.println(name);
    }

    // create an ascending index on the "i" field
    collection.createIndex(new Document("i", 1));

    // list the indexes on the collection
    for (final Document index : collection.listIndexes()) {
        System.out.println(index);
    }

    // create a text index on the "content" field
    collection.createIndex(new Document("content", "text"));

    collection.insertOne(new Document("_id", 0).append("content", "textual content"));
    collection.insertOne(new Document("_id", 1).append("content", "additional content"));
    collection.insertOne(new Document("_id", 2).append("content", "irrelevant content"));

    // Find using the text index
    Document search = new Document("$search", "textual content -irrelevant");
    Document textSearch = new Document("$text", search);
    long matchCount = collection.count(textSearch);
    System.out.println("Text search matches: " + matchCount);

    // Find using the $language operator
    textSearch = new Document("$text", search.append("$language", "english"));
    matchCount = collection.count(textSearch);
    System.out.println("Text search matches (english): " + matchCount);

    // Find the highest scoring match
    Document projection = new Document("score", new Document("$meta", "textScore"));
    myDoc = collection.find(textSearch).projection(projection).first();
    System.out.println("Highest scoring document: " + myDoc);

    // release resources
    mongoClient.close();
}