Example usage for com.mongodb.client MongoDatabase listCollectionNames

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

Introduction

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

Prototype

MongoIterable<String> listCollectionNames();

Source Link

Document

Gets the names of all the collections in this database.

Usage

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();//from ww w  .  j  av a  2  s  .  co  m

        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/*w w w .ja  va  2 s  .  c  o 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:mp6uf2pt3.MP6UF2PT3.java

/**
 * @param args the command line arguments
 *//*from  w w  w .  ja  v a2 s .  co m*/
public static void main(String[] args) {

    MongoClient mongoClient = new MongoClient();
    MongoDatabase database = mongoClient.getDatabase("consultes");

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

    MongoCollection<Document> col = database.getCollection("restaurants");

}

From source file:mypackage.DBInformation.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        try {/*from   w ww  . ja v a  2  s.c  o  m*/
            String dbName = request.getParameter("dbname");
            MongoClient mongoClient = new MongoClient("localhost", 27017);
            HttpSession httpSession = request.getSession(false);
            MongoDatabase mongoDatabase = mongoClient.getDatabase(dbName);
            MongoIterable<String> mongoIterable = mongoDatabase.listCollectionNames();
            MongoCursor<String> mongoCursor = mongoIterable.iterator();
            JSONObject jSONObject = new JSONObject();
            JSONObject jSONObject1 = new JSONObject();
            JSONArray jSONArray = new JSONArray();
            int i = 0;
            while (mongoCursor.hasNext()) {
                jSONArray.put(mongoCursor.next());
                i++;
            }
            jSONObject.put("db", jSONArray);
            jSONObject.put("counter", i);
            out.println(jSONObject);

        } catch (JSONException e) {

        }

    }
}

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));
        }/*w w  w  .  j  a  v a2 s  .c  om*/
    } else {
        db.createCollection(collectionName,
                new CreateCollectionOptions().capped(true).sizeInBytes(sizeInBytes));
    }

}

From source file:org.apache.metamodel.mongodb.mongo3.MongoDbDataContext.java

License:Apache License

/**
 * Performs an analysis of the available collections in a Mongo {@link DB}
 * instance and tries to detect the table's structure based on the first
 * 1000 documents in each collection.//from   w w  w .j  a v  a  2  s  . c om
 *
 * @param mongoDb
 *            the mongo db to inspect
 * @return a mutable schema instance, useful for further fine tuning by the
 *         user.
 * @see #detectTable(MongoDatabase, String)
 */
public static SimpleTableDef[] detectSchema(MongoDatabase mongoDb) {
    MongoIterable<String> collectionNames = mongoDb.listCollectionNames();
    List<SimpleTableDef> result = new ArrayList<>();

    for (String collectionName : collectionNames) {
        SimpleTableDef table = detectTable(mongoDb, collectionName);
        result.add(table);
    }
    return result.toArray(new SimpleTableDef[0]);
}

From source file:org.bananaforscale.cormac.dao.AbstractDataService.java

License:Apache License

/**
 * Retrieves the names of the collections in a database.
 *
 * @param databaseName the name of the database
 * @return a {@link Set} of collection names
 *///from  w  w  w  .j  av a  2s.  co  m
protected Set<String> getCollectionNames(final String databaseName) {
    final MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);
    final Set<String> collectionSet = new HashSet<>();
    final MongoCursor<String> cursor = mongoDatabase.listCollectionNames().iterator();
    while (cursor.hasNext()) {
        collectionSet.add(cursor.next());
    }
    return collectionSet;
}

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

License:Apache License

private SingleMongoDatabase createMongoDatabaseAndItsCollections(MongoDatabase database) {
    SingleMongoDatabase singleMongoDatabase = new SingleMongoDatabase(database.getName());

    MongoIterable<String> collectionNames = database.listCollectionNames();
    for (String collectionName : collectionNames) {
        singleMongoDatabase.addCollection(new SingleMongoCollection(collectionName, database.getName()));
    }/*from  w  w w .  j  a  v a 2  s.c om*/
    return singleMongoDatabase;
}

From source file:org.flywaydb.core.internal.command.MongoClean.java

License:Apache License

@Override
public void clean() throws FlywayException {
    if (cleanDisabled) {
        throw new FlywayException(
                "Unable to execute clean as it has been disabled with the \"flyway.cleanDisabled\" property.");
    }/*from  w ww  .  ja  v a  2  s . c o  m*/

    for (final MongoFlywayCallback callback : callbacks) {
        callback.beforeClean(client);
    }

    for (String dbName : client.listDatabaseNames()) {
        MongoDatabase db = client.getDatabase(dbName);
        for (String collectionName : db.listCollectionNames()) {
            db.getCollection(collectionName).drop();
        }
    }
    LOG.info("Successfully cleaned Mongo.");

    for (final MongoFlywayCallback callback : callbacks) {
        callback.afterClean(client);
    }
}

From source file:org.flywaydb.core.internal.dbsupport.mongo.MongoDatabaseUtil.java

License:Apache License

/**
 * Checks whether a Mongo database is empty.
 *
 * @param mongoDb a MongoDatabase object
 * @return {@code true} if it is, {@code false} if isn't. Returns {@code false} if the database does not exist.
 * @throws FlywayException when the check fails.
 *//*from  ww w . j a  v  a 2  s.c o  m*/
public static boolean empty(MongoDatabase mongoDb) throws FlywayException {
    try {
        MongoIterable<String> collectionIterable = mongoDb.listCollectionNames();
        return !collectionIterable.iterator().hasNext();
    } catch (MongoException e) {
        throw new FlywayException("Unable to check whether Mongo database " + mongoDb.getName() + " is empty",
                e);
    }
}