Example usage for com.mongodb MongoClient getDB

List of usage examples for com.mongodb MongoClient getDB

Introduction

In this page you can find the example usage for com.mongodb MongoClient getDB.

Prototype

@Deprecated 
public DB getDB(final String dbName) 

Source Link

Document

Gets a database object.

Usage

From source file:es.upv.dsic.elp.iJulienne.MongoDB.java

License:Open Source License

public static String loadData(String maudeInput) {
    String res = null;// w  w  w .j  a va2  s  . co  m
    MongoClient mongo;
    DB db;

    //WARNING: Configure with your own data
    try {
        mongo = new MongoClient("YOUR_SERVER_ADDRESS", YOUR_SERVER_PORT);
    } catch (UnknownHostException e) {
        return null;
    }

    db = mongo.getDB("ijulienne");
    //WARNING: Configure with your own data
    boolean auth = db.authenticate("YOUR_USER", "YOUR_PASSWORD".toCharArray());
    if (auth) {
        DBCollection table = db.getCollection("ijulienne");
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("input", maudeInput);

        DBCursor cursor = table.find(searchQuery);
        if (cursor.hasNext())
            res = cursor.next().get("output").toString();
    }
    mongo.close();
    return res;
}

From source file:es.upv.dsic.elp.iJulienne.MongoDB.java

License:Open Source License

public static void saveData(String maudeInput, String maudeOutput) {
    MongoClient mongo;
    DB db;//from   w  w  w .j av  a 2s .  c om

    //WARNING: Configure with your own data
    try {
        mongo = new MongoClient("YOUR_SERVER_ADDRESS", YOUR_SERVER_PORT);
    } catch (UnknownHostException e) {
        return;
    }

    db = mongo.getDB("ijulienne");
    //WARNING: Configure with your own data
    boolean auth = db.authenticate("YOUR_USER", "YOUR_PASSWORD".toCharArray());
    if (auth) {
        DBCollection table = db.getCollection("ijulienne");
        BasicDBObject document = new BasicDBObject();
        document.put("input", maudeInput);
        document.put("output", maudeOutput);
        table.insert(document);
    }
    mongo.close();
}

From source file:example.AggregationExample.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes no args//w w  w.ja  va 2s.  c o  m
 * @throws UnknownHostException if it cannot connect to a MongoDB instance at localhost:27017
 */
public static void main(final String[] args) throws UnknownHostException {
    // connect to the local database server
    MongoClient mongoClient = new MongoClient();

    // get handle to "mydb"
    DB db = mongoClient.getDB("mydb");

    // Authenticate - optional
    // boolean auth = db.authenticate("foo", "bar");

    // Add some sample data
    DBCollection coll = db.getCollection("aggregationExample");
    coll.insert(new BasicDBObjectBuilder().add("employee", 1).add("department", "Sales").add("amount", 71)
            .add("type", "airfare").get());
    coll.insert(new BasicDBObjectBuilder().add("employee", 2).add("department", "Engineering").add("amount", 15)
            .add("type", "airfare").get());
    coll.insert(new BasicDBObjectBuilder().add("employee", 4).add("department", "Human Resources")
            .add("amount", 5).add("type", "airfare").get());
    coll.insert(new BasicDBObjectBuilder().add("employee", 42).add("department", "Sales").add("amount", 77)
            .add("type", "airfare").get());

    // create our pipeline operations, first with the $match
    DBObject match = new BasicDBObject("$match", new BasicDBObject("type", "airfare"));

    // build the $projection operation
    DBObject fields = new BasicDBObject("department", 1);
    fields.put("amount", 1);
    fields.put("_id", 0);
    DBObject project = new BasicDBObject("$project", fields);

    // Now the $group operation
    DBObject groupFields = new BasicDBObject("_id", "$department");
    groupFields.put("average", new BasicDBObject("$avg", "$amount"));
    DBObject group = new BasicDBObject("$group", groupFields);

    // Finally the $sort operation
    DBObject sort = new BasicDBObject("$sort", new BasicDBObject("average", -1));

    // run aggregation
    List<DBObject> pipeline = Arrays.asList(match, project, group, sort);
    AggregationOutput output = coll.aggregate(pipeline);

    // Output the results
    for (DBObject result : output.results()) {
        System.out.println(result);
    }

    // Aggregation Cursor
    AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100)
            .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build();

    Cursor cursor = coll.aggregate(pipeline, aggregationOptions);
    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }

    // clean up
    db.dropDatabase();
    mongoClient.close();
}

From source file:example.GSSAPICredentialsExample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException, InterruptedException {
    // Set this property to avoid the default behavior where the program prompts on the command line for username/password
    //        Security.setProperty("auth.login.defaultCallbackHandler", "example.DefaultSecurityCallbackHandler");

    String server = args[0];/*  ww w .j  a  v  a2 s .c  o  m*/
    String user = args[1];
    String databaseName = args[2];

    System.out.println("javax.security.auth.useSubjectCredsOnly: "
            + System.getProperty("javax.security.auth.useSubjectCredsOnly"));
    System.out.println("java.security.krb5.realm: " + System.getProperty("java.security.krb5.realm"));
    System.out.println("java.security.krb5.kdc: " + System.getProperty("java.security.krb5.kdc"));
    System.out.println(
            "auth.login.defaultCallbackHandler: " + Security.getProperty("auth.login.defaultCallbackHandler"));
    System.out.println("login.configuration.provider: " + Security.getProperty("login.configuration.provider"));
    System.out.println(
            "java.security.auth.login.config: " + Security.getProperty("java.security.auth.login.config"));
    System.out.println("login.config.url.1: " + Security.getProperty("login.config.url.1"));
    System.out.println("login.config.url.2: " + Security.getProperty("login.config.url.2"));
    System.out.println("login.config.url.3: " + Security.getProperty("login.config.url.3"));

    System.out.println("server: " + server);
    System.out.println("user: " + user);
    System.out.println("database: " + databaseName);

    System.out.println();

    MongoClient mongoClient = new MongoClient(new ServerAddress(server),
            asList(MongoCredential.createGSSAPICredential(user).withMechanismProperty("SERVICE_NAME",
                    "mongodb")),
            new MongoClientOptions.Builder().socketKeepAlive(true).socketTimeout(30000).build());
    DB testDB = mongoClient.getDB(databaseName);

    System.out.println("Insert result: " + testDB.getCollection("test").insert(new BasicDBObject()));
    System.out.println("Count: " + testDB.getCollection("test").count());
}

From source file:example.MongoCredentialsExample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    String server = args[0];/*w  w w.  j av  a  2s .  co  m*/
    String user = args[1];
    String password = args[2];
    String databaseName = args[3];

    System.out.println("server: " + server);
    System.out.println("user: " + user);
    System.out.println("database: " + databaseName);

    System.out.println();

    MongoClient mongoClient = new MongoClient(new ServerAddress(server),
            asList(MongoCredential.createMongoCRCredential(user, "test", password.toCharArray())),
            new MongoClientOptions.Builder().socketKeepAlive(true).socketTimeout(30000).build());
    DB testDB = mongoClient.getDB(databaseName);

    System.out.println("Count: " + testDB.getCollection("test").count());

    System.out.println("Insert result: " + testDB.getCollection("test").insert(new BasicDBObject()));

}

From source file:example.QuickTour.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes no args//from   w  ww  .j av a  2  s.co  m
 * @throws UnknownHostException if it cannot connect to a MongoDB instance at localhost:27017
 */
public static void main(final String[] args) throws UnknownHostException {
    // connect to the local database server
    MongoClient mongoClient = new MongoClient();

    // get handle to "mydb"
    DB db = mongoClient.getDB("mydb");

    // Authenticate - optional
    // boolean auth = db.authenticate("foo", "bar");

    // get a list of the collections in this database and print them out
    Set<String> collectionNames = db.getCollectionNames();
    for (final String s : collectionNames) {
        System.out.println(s);
    }

    // get a collection object to work with
    DBCollection testCollection = db.getCollection("testCollection");

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

    // make a document and insert it
    BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("type", "database").append("count", 1)
            .append("info", new BasicDBObject("x", 203).append("y", 102));

    testCollection.insert(doc);

    // get it (since it's the only one in there since we dropped the rest earlier on)
    DBObject myDoc = testCollection.findOne();
    System.out.println(myDoc);

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

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

    // now use a query to get 1 document out
    BasicDBObject query = new BasicDBObject("i", 71);
    cursor = testCollection.find(query);

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

    // now use a range query to get a larger subset
    query = new BasicDBObject("i", new BasicDBObject("$gt", 50)); // i.e. find all where i > 50
    cursor = testCollection.find(query);

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

    // range query with multiple constraints
    query = new BasicDBObject("i", new BasicDBObject("$gt", 20).append("$lte", 30)); // i.e.   20 < i <= 30
    cursor = testCollection.find(query);

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

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

    // list the indexes on the collection
    List<DBObject> list = testCollection.getIndexInfo();
    for (final DBObject o : list) {
        System.out.println(o);
    }

    // See if the last operation had an error
    System.out.println("Last error : " + db.getLastError());

    // see if any previous operation had an error
    System.out.println("Previous error : " + db.getPreviousError());

    // force an error
    db.forceError();

    // See if the last operation had an error
    System.out.println("Last error : " + db.getLastError());

    db.resetError();

    // release resources
    mongoClient.close();
}

From source file:example.QuickTourAdmin.java

License:Apache License

public static void main(String[] args) throws Exception {

    // connect to the local database server 
    MongoClient mongoClient = new MongoClient();

    // Authenticate - optional
    // boolean auth = db.authenticate("foo", "bar");

    // get db names
    for (String s : mongoClient.getDatabaseNames()) {
        System.out.println(s);// w w w.  ja  va  2  s.  c  o m
    }

    // get a db
    DB db = mongoClient.getDB("com_mongodb_MongoAdmin");

    // do an insert so that the db will really be created.  Calling getDB() doesn't really take any
    // action with the server 
    db.getCollection("testcollection").insert(new BasicDBObject("i", 1));
    for (String s : mongoClient.getDatabaseNames()) {
        System.out.println(s);
    }

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

    for (String s : mongoClient.getDatabaseNames()) {
        System.out.println(s);
    }
}

From source file:example.ScramSha1CredentialsExample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    String server = args[0];/*from w w  w.  j  a  va  2s  .  c o  m*/
    String user = args[1];
    String password = args[2];
    String source = args[3];

    System.out.println("server: " + server);
    System.out.println("user: " + user);
    System.out.println("source: " + source);

    System.out.println();

    MongoClient mongoClient = new MongoClient(new ServerAddress(server),
            Arrays.asList(MongoCredential.createScramSha1Credential(user, source, password.toCharArray())),
            new MongoClientOptions.Builder().build());
    DB testDB = mongoClient.getDB("test");

    System.out.println("Count: " + testDB.getCollection("test").count());

    System.out.println("Insert result: " + testDB.getCollection("test").insert(new BasicDBObject()));
}

From source file:example.springdata.mongodb.util.MongosSystemForTestFactory.java

License:Apache License

private void initializeReplicaSet(Entry<String, List<IMongodConfig>> entry) throws Exception {
    String replicaName = entry.getKey();
    List<IMongodConfig> mongoConfigList = entry.getValue();

    if (mongoConfigList.size() < 3) {
        throw new Exception("A replica set must contain at least 3 members.");
    }//from   w w w .j av  a2  s  . co m
    // Create 3 mongod processes
    for (IMongodConfig mongoConfig : mongoConfigList) {
        if (!mongoConfig.replication().getReplSetName().equals(replicaName)) {
            throw new Exception("Replica set name must match in mongo configuration");
        }
        IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder().defaultsWithLogger(Command.MongoD, logger)
                .processOutput(outputFunction.apply(Command.MongoD)).build();
        MongodStarter starter = MongodStarter.getInstance(runtimeConfig);
        MongodExecutable mongodExe = starter.prepare(mongoConfig);
        MongodProcess process = mongodExe.start();
        mongodProcessList.add(process);
    }
    Thread.sleep(1000);
    MongoClientOptions mo = MongoClientOptions.builder().connectTimeout(10).build();
    MongoClient mongo = new MongoClient(
            new ServerAddress(mongoConfigList.get(0).net().getServerAddress().getHostName(),
                    mongoConfigList.get(0).net().getPort()),
            mo);
    DB mongoAdminDB = mongo.getDB(ADMIN_DATABASE_NAME);

    CommandResult cr = mongoAdminDB.command(new BasicDBObject("isMaster", 1));
    logger.info("isMaster: {}", cr);

    // Build BSON object replica set settings
    DBObject replicaSetSetting = new BasicDBObject();
    replicaSetSetting.put("_id", replicaName);
    BasicDBList members = new BasicDBList();
    int i = 0;
    for (IMongodConfig mongoConfig : mongoConfigList) {
        DBObject host = new BasicDBObject();
        host.put("_id", i++);
        host.put("host",
                mongoConfig.net().getServerAddress().getHostName() + ":" + mongoConfig.net().getPort());
        members.add(host);
    }

    replicaSetSetting.put("members", members);
    logger.info(replicaSetSetting.toString());
    // Initialize replica set
    cr = mongoAdminDB.command(new BasicDBObject("replSetInitiate", replicaSetSetting));
    logger.info("replSetInitiate: {}", cr);

    Thread.sleep(5000);
    cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1));
    logger.info("replSetGetStatus: {}", cr);

    // Check replica set status before to proceed
    while (!isReplicaSetStarted(cr)) {
        logger.info("Waiting for 3 seconds...");
        Thread.sleep(1000);
        cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1));
        logger.info("replSetGetStatus: {}", cr);
    }

    mongo.close();
    mongo = null;
}

From source file:example.springdata.mongodb.util.RequiresMongoDB.java

License:Apache License

private void initCurrentVersion() {

    if (currentVersion == null) {
        try {//from   www  .  ja v  a2  s .  c om
            MongoClient client;
            client = new MongoClient(host, port);
            DB db = client.getDB("test");
            CommandResult result = db.command(new BasicDBObjectBuilder().add("buildInfo", 1).get());
            this.currentVersion = Version.parse(result.get("version").toString());
        } catch (com.mongodb.MongoTimeoutException | UnknownHostException e) {
            throw new AssumptionViolatedException("Seems as mongodb server is not running.", e);
        }
    }

}