Example usage for com.mongodb.client MongoDatabase runCommand

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

Introduction

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

Prototype

Document runCommand(Bson command);

Source Link

Document

Executes the given command in the context of the current database with a read preference of ReadPreference#primary() .

Usage

From source file:mongodb.QuickTourAdmin.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args//from w  w w.  j  a v  a  2s  . 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: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 ww.  j  a  v  a2s . c o m
    } else {
        db.createCollection(collectionName,
                new CreateCollectionOptions().capped(true).sizeInBytes(sizeInBytes));
    }

}

From source file:org.apache.drill.exec.store.mongo.MongoGroupScan.java

License:Apache License

private boolean isShardedCluster(MongoClient client) {
    MongoDatabase db = client.getDatabase(scanSpec.getDbName());
    String msg = db.runCommand(new Document("isMaster", 1)).getString("msg");
    return msg == null ? false : msg.equals("isdbgrid");
}

From source file:org.apache.drill.exec.store.mongo.MongoGroupScan.java

License:Apache License

@SuppressWarnings("unchecked")
private Set<ServerAddress> getPreferredHosts(MongoClient client, List<String> hosts) {
    Set<ServerAddress> addressList = Sets.newHashSet();
    MongoDatabase db = client.getDatabase(scanSpec.getDbName());
    ReadPreference readPreference = client.getReadPreference();
    Document command = db.runCommand(new Document("isMaster", 1));

    final String primaryHost = command.getString("primary");
    final List<String> hostsList = (List<String>) command.get("hosts");

    switch (readPreference.getName().toUpperCase()) {
    case "PRIMARY":
    case "PRIMARYPREFERRED":
        if (primaryHost == null) {
            return null;
        }//www .j  av  a 2 s  .  c om
        addressList.add(new ServerAddress(primaryHost));
        return addressList;
    case "SECONDARY":
    case "SECONDARYPREFERRED":
        if (primaryHost == null || hostsList == null) {
            return null;
        }
        hostsList.remove(primaryHost);
        for (String host : hostsList) {
            addressList.add(new ServerAddress(host));
        }
        return addressList;
    case "NEAREST":
        if (hostsList == null) {
            return null;
        }
        for (String host : hostsList) {
            addressList.add(new ServerAddress(host));
        }
        return addressList;
    default:
        return null;
    }
}

From source file:org.flywaydb.core.internal.dbsupport.MongoScript.java

License:Apache License

/**
 * Executes the MongoStatements found in this MongoScript against the database.
 *
 * @param mongoClient The MongoClient to use to execute this script.
 *///from   ww  w .j ava2 s .  c  o  m
public void execute(final MongoClient mongoClient) {
    MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);
    for (MongoStatement mongoStatement : mongoStatements) {
        LOG.debug("Executing MONGO: " + mongoStatement);
        try {
            mongoDatabase.runCommand(Document.parse(mongoStatement.getJson()));
        } catch (JsonParseException jpe) {
            MongoException e = new MongoException("Cannot parse mongo command. " + jpe.getMessage());
            throw new FlywayMongoScriptException(resource, mongoStatement, e);
        } catch (MongoException e) {
            throw new FlywayMongoScriptException(resource, mongoStatement, e);
        }
    }
}

From source file:org.netbeans.modules.mongodb.ui.explorer.CollectionNode.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
protected Sheet createSheet() {
    Sheet sheet = Sheet.createDefault();
    Sheet.Set set = Sheet.createPropertiesSet();
    MongoDatabase db = getLookup().lookup(MongoDatabase.class);
    BsonDocument commandDocument = new BsonDocument("collStats", new BsonString(collection.getName()));
    try {//  w  w  w  . ja v  a2  s .com
        Document result = db.runCommand(commandDocument);
        set.put(new LocalizedProperties(CollectionNode.class).fromDocument(result).toArray());
        sheet.put(set);
    } catch (MongoException ex) {
        if (MongoErrorCode.of(ex) != MongoErrorCode.Unauthorized) {
            DialogNotification.error(ex);
        }
    }
    return sheet;
}

From source file:org.netbeans.modules.mongodb.ui.explorer.DBNode.java

License:Open Source License

@Override
protected Sheet createSheet() {
    Sheet sheet = Sheet.createDefault();
    Sheet.Set set = Sheet.createPropertiesSet();
    MongoDatabase db = getLookup().lookup(MongoDatabase.class);
    BsonDocument commandDocument = new BsonDocument("dbStats", new BsonInt32(1)).append("scale",
            new BsonInt32(1));
    try {//from  w ww .jav  a 2  s .  co  m
        Document result = db.runCommand(commandDocument);
        set.put(new LocalizedProperties(DBNode.class).fromDocument(result).toArray());
        sheet.put(set);
    } catch (MongoException ex) {
        if (MongoErrorCode.of(ex) != MongoErrorCode.Unauthorized) {
            DialogNotification.error(ex);
        }
    }
    return sheet;
}