List of usage examples for com.mongodb Mongo getDB
@Deprecated public DB getDB(final String dbName)
From source file:de.fhg.igd.mongomvcc.impl.MongoDBVDatabase.java
License:Open Source License
private void connectInternal(String name, Mongo mongo) { _buildInfo = initBuildInfo(mongo);/*from w w w .j a v a 2 s .c o m*/ _db = mongo.getDB(name); _counter = new MongoDBVCounter(_db); _tree = new Tree(_db); //create root commit and master branch if needed if (_tree.isEmpty()) { Commit root = new Commit(_counter.getNextId(), 0, 0, Collections.<String, IdMap>emptyMap()); _tree.addCommit(root); _tree.addBranch(VConstants.MASTER, root.getCID()); } }
From source file:de.fhg.igd.mongomvcc.impl.MongoDBVDatabase.java
License:Open Source License
/** * Obtains build information from the database instance. If any value is * not available, this method will return <code>null</code>. * @param mongo the database/* ww w . j a va2s . co m*/ * @return the build information or <code>null</code> */ private static BuildInfo initBuildInfo(Mongo mongo) { DB db = mongo.getDB("admin"); if (db == null) { return null; } CommandResult cr = db.command("buildInfo"); String version = (String) cr.get("version"); if (version == null) { return null; } String[] vss = version.split("\\."); if (vss.length <= 2) { return null; } Integer maxBsonObjectSize = (Integer) cr.get("maxBsonObjectSize"); if (maxBsonObjectSize == null) { maxBsonObjectSize = Integer.valueOf(0); } try { return new BuildInfo(Integer.parseInt(vss[0]), Integer.parseInt(vss[1]), Integer.parseInt(vss[2]), maxBsonObjectSize); } catch (NumberFormatException e) { return null; } }
From source file:de.flapdoodle.embed.mongo.tests.MongodForTestsFactory.java
License:Apache License
/** * Creates a new DB with unique name for connection. *//* w w w.j ava2 s . com*/ public DB newDB(Mongo mongo) { return mongo.getDB(UUID.randomUUID().toString()); }
From source file:de.flapdoodle.embed.mongo.tests.MongosSystemForTestFactory.java
License:Apache License
private void configureMongos() throws Exception { CommandResult cr;//from ww w. j a v a2 s . co m MongoOptions mo = new MongoOptions(); mo.autoConnectRetry = true; Mongo mongo = new Mongo( new ServerAddress(this.config.net().getServerAddress().getHostName(), this.config.net().getPort()), mo); DB mongoAdminDB = mongo.getDB(ADMIN_DATABASE_NAME); // Add shard from the replica set list for (Entry<String, List<IMongodConfig>> entry : this.replicaSets.entrySet()) { String replicaName = entry.getKey(); String command = ""; for (IMongodConfig mongodConfig : entry.getValue()) { if (command.isEmpty()) { command = replicaName + "/"; } else { command += ","; } command += mongodConfig.net().getServerAddress().getHostName() + ":" + mongodConfig.net().getPort(); } logger.info("Execute add shard command: " + command); cr = mongoAdminDB.command(new BasicDBObject("addShard", command)); logger.info(cr.toString()); } logger.info("Execute list shards."); cr = mongoAdminDB.command(new BasicDBObject("listShards", 1)); logger.info(cr.toString()); // Enabled sharding at database level logger.info("Enabled sharding at database level"); cr = mongoAdminDB.command(new BasicDBObject("enableSharding", this.shardDatabase)); logger.info(cr.toString()); // Create index in sharded collection logger.info("Create index in sharded collection"); DB db = mongo.getDB(this.shardDatabase); db.getCollection(this.shardCollection).ensureIndex(this.shardKey); // Shard the collection logger.info("Shard the collection: " + this.shardDatabase + "." + this.shardCollection); DBObject cmd = new BasicDBObject(); cmd.put("shardCollection", this.shardDatabase + "." + this.shardCollection); cmd.put("key", new BasicDBObject(this.shardKey, 1)); cr = mongoAdminDB.command(cmd); logger.info(cr.toString()); logger.info("Get info from config/shards"); DBCursor cursor = mongo.getDB("config").getCollection("shards").find(); while (cursor.hasNext()) { DBObject item = cursor.next(); logger.info(item.toString()); } }
From source file:edu.sjsu.carbonated.client.MongoDBDOA.java
License:Apache License
public static void main(String[] args) throws Exception { // connect to the local database server Mongo m = new Mongo(); // get handle to "mydb" DB db = m.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> colls = db.getCollectionNames(); for (String s : colls) { System.out.println(s);/*w w w. j a v a 2 s .co m*/ } // get a collection object to work with DBCollection coll = db.getCollection("testCollection"); // drop all the data in it coll.drop(); // make a document and insert it BasicDBObject doc = new BasicDBObject(); doc.put("test", new AlbumResource("name", "desc", "user", "asdf")); doc.put("name", "MongoDB"); doc.put("type", "database"); doc.put("count", 1); BasicDBObject info = new BasicDBObject(); info.put("x", 203); info.put("y", 102); doc.put("info", info); coll.insert(doc); // get it (since it's the only one in there since we dropped the rest earlier on) DBObject myDoc = coll.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++) { coll.insert(new BasicDBObject().append("i", i)); } System.out .println("total # of documents after inserting 100 small ones (should be 101) " + coll.getCount()); // lets get all the documents in the collection and print them out DBCursor cur = coll.find(); while (cur.hasNext()) { System.out.println(cur.next()); } // now use a query to get 1 document out BasicDBObject query = new BasicDBObject(); query.put("i", 71); cur = coll.find(query); while (cur.hasNext()) { System.out.println(cur.next()); } // now use a range query to get a larger subset query = new BasicDBObject(); query.put("i", new BasicDBObject("$gt", 50)); // i.e. find all where i > 50 cur = coll.find(query); while (cur.hasNext()) { System.out.println(cur.next()); } // range query with multiple contstraings query = new BasicDBObject(); query.put("i", new BasicDBObject("$gt", 20).append("$lte", 30)); // i.e. 20 < i <= 30 cur = coll.find(query); while (cur.hasNext()) { System.out.println(cur.next()); } // create an index on the "i" field coll.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending // list the indexes on the collection List<DBObject> list = coll.getIndexInfo(); for (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(); }
From source file:es.devcircus.mongodb_examples.hello_world.Main.java
License:Open Source License
/** * Mtodo que nos permite crear una nueva conexin con nuestra base de * datos.//from w ww . j a va2 s .c om */ public static void makingAConnection() { try { System.out.println("---------------------------------------------------------------"); System.out.println(" Making A Connection "); System.out.println("---------------------------------------------------------------"); System.out.println(); /*Making A Connection To make a connection to a MongoDB, you need to have at the minimum, * the name of a database to connect to. The database doesn't have * to exist - if it doesn't, MongoDB will create it for you. Additionally, you can specify the server address and port when connecting. * The following example shows three ways to connect to the database * mydb on the local machine :*/ Mongo m = new Mongo(); // or //Mongo m = new Mongo( "localhost" ); // or //Mongo m = new Mongo( "localhost" , 27017 ); db = m.getDB(DB_NAME); System.out.println(" Conexin establecida..: " + db.getName()); /*At this point, the db object will be a connection to a MongoDB * server for the specified database. With it, you can do further * operations. Note: The Mongo object instance actually represents a pool of connections * to the database; you will only need one object of class Mongo * even with multiple threads. See the concurrency doc page for more * information. The Mongo class is designed to be thread safe and shared among threads. * Typically you create only 1 instance for a given DB cluster and * use it across your app. If for some reason you decide to create * many mongo intances, note that: all resource usage limits (max connections, etc) apply per mongo instance to dispose of an instance, make sure you call mongo.close() to clean * up resources*/ } catch (UnknownHostException | MongoException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:essex.bigessexnew.MongoListener.java
public MongoListener(String host, String port, String db, String collection) { Mongo mongo = new Mongo(host, Integer.getInteger(port)); this.collection = mongo.getDB(db).getCollection(collection); }
From source file:essex.bigessexnew.OplogListener.java
public OplogListener(String host, String port, String db, String collection) { Mongo mongo = new Mongo(host, Integer.parseInt(port)); this.collection = mongo.getDB(db).getCollection(collection); }
From source file:essex.bigessexnew.OplogListener.java
private void performListenTask(DBCursor cur) { EssexDataHandler dh = new EssexDataHandler(Params.getProperty("essexHostPath")); Mongo mongo2 = new Mongo(Params.getProperty("host"), Integer.parseInt(Params.getProperty("port"))); DBCollection realCollection = mongo2.getDB(Params.getProperty("shardedDB")) .getCollection(Params.getProperty("shardedCollection")); Runnable task = () -> {/* w w w .j a v a 2 s .c o m*/ System.out.println("\tWaiting for events"); while (cur.hasNext()) { DBObject obj = cur.next(); System.out.println(obj.toString()); JSONObject output = new JSONObject(JSON.serialize(obj)); String id = output.getJSONObject("o").getJSONObject("_id").getString("$oid"); String opType = output.getString("op"); String content = retrieveContent(realCollection, id); dh.handle(content, opType); } }; new Thread(task).start(); }
From source file:essex.bigessexnew.TwitterStreamHandler.java
public TwitterStreamHandler(String host, String port, String DBName, String collectionName) { Mongo mongoClient = new Mongo(host, Integer.parseInt(port)); collection = mongoClient.getDB(DBName).getCollection(collectionName); }