List of usage examples for com.mongodb Mongo getDB
@Deprecated public DB getDB(final String dbName)
From source file:org.einherjer.week2.samples.FieldSelectionSample.java
License:Apache License
public static void main(String[] args) throws UnknownHostException { Mongo client = new Mongo(); DB db = client.getDB("course"); DBCollection collection = db.getCollection("fieldSelectionSample"); collection.drop();/*from w ww . j a v a2 s. c o m*/ Random rand = new Random(); // insert 10 documents with two random integers for (int i = 0; i < 10; i++) { collection.insert(new BasicDBObject("x", rand.nextInt(2)).append("y", rand.nextInt(100)).append("z", rand.nextInt(1000))); } DBObject query = QueryBuilder.start("x").is(0).and("y").greaterThan(10).lessThan(70).get(); //use second find parameter to filter the returned fields DBCursor cursor = collection.find(query, new BasicDBObject("y", true).append("_id", false)); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println(cur); } } finally { cursor.close(); } }
From source file:org.einherjer.week2.samples.FindAndModifySample.java
License:Apache License
private static DBCollection createCollection() throws UnknownHostException { Mongo client = new Mongo(); DB db = client.getDB("course"); return db.getCollection("findModifySample"); }
From source file:org.einherjer.week2.samples.FindCriteriaSample.java
License:Apache License
public static void main(String[] args) throws UnknownHostException { Mongo client = new Mongo(); DB db = client.getDB("course"); DBCollection collection = db.getCollection("findCriteriaSample"); collection.drop();//from w ww.j a v a 2s. co m // insert 10 documents with two random integers for (int i = 0; i < 10; i++) { collection .insert(new BasicDBObject("x", new Random().nextInt(2)).append("y", new Random().nextInt(100))); } //1- The query document can be created by using a QueryBuilder... QueryBuilder builder = QueryBuilder.start("x").is(0).and("y").greaterThan(10).lessThan(70); //2- or, the query document can be created manually DBObject query = new BasicDBObject("x", 0).append("y", new BasicDBObject("$gt", 10).append("$lt", 90)); System.out.println("\nCount:"); long count = collection.count(builder.get()); System.out.println(count); System.out.println("\nFind all: "); DBCursor cursor = collection.find(builder.get()); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println(cur); } } finally { cursor.close(); } }
From source file:org.einherjer.week2.samples.FindSample.java
License:Apache License
public static void main(String[] args) throws UnknownHostException { Mongo client = new Mongo(); DB db = client.getDB("course"); DBCollection collection = db.getCollection("findSample"); collection.drop();//w w w. ja v a 2s.c o m // insert 10 documents with a random integer as the value of field "x" for (int i = 0; i < 10; i++) { collection.insert(new BasicDBObject("x", new Random().nextInt(100))); } System.out.println("Find one:"); DBObject one = collection.findOne(); System.out.println(one); System.out.println("\nFind all: "); DBCursor cursor = collection.find(); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println(cur); } } finally { cursor.close(); } System.out.println("\nCount:"); long count = collection.count(); System.out.println(count); }
From source file:org.einherjer.week2.samples.InsertSample.java
License:Apache License
public static void main(String[] args) throws UnknownHostException { Mongo client = new Mongo(); DB courseDB = client.getDB("course"); DBCollection collection = courseDB.getCollection("insertSample"); collection.drop();//from w w w . j a va2 s . c o m DBObject doc = new BasicDBObject().append("x", 1); System.out.println(doc); collection.insert(doc); System.out.println(doc); //_id field gets generated DBObject doc2 = new BasicDBObject("_id", new ObjectId()).append("x", 1); System.out.println(doc2); collection.insert(doc2); System.out.println(doc2); //same as doc1 DBObject doc3 = new BasicDBObject("_id", "123").append("x", 1); System.out.println(doc3); collection.insert(doc3); System.out.println(doc3); //_id field set by to a type different than ObjectId collection.insert(doc); //duplicate exception }
From source file:org.einherjer.week2.samples.SortSkipLimitSample.java
License:Apache License
public static void main(String[] args) throws UnknownHostException { Mongo client = new Mongo(); DB db = client.getDB("course"); DBCollection lines = db.getCollection("sortSkipLimitSample"); lines.drop();/* w w w . j ava 2 s . co m*/ Random rand = new Random(); // insert 10 lines with random start and end points for (int i = 0; i < 10; i++) { lines.insert(new BasicDBObject("_id", i) .append("start", new BasicDBObject("x", rand.nextInt(2)).append("y", rand.nextInt(90) + 10)) .append("end", new BasicDBObject("x", rand.nextInt(2)).append("y", rand.nextInt(90) + 10))); } DBCursor cursor = lines.find().sort(new BasicDBObject("start.x", 1).append("start.y", -1)).skip(2) .limit(10); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println(cur); } } finally { cursor.close(); } }
From source file:org.einherjer.week2.samples.UpdateRemoveSample.java
License:Apache License
private static DBCollection createCollection() throws UnknownHostException { Mongo client = new Mongo(); DB db = client.getDB("course"); DBCollection collection = db.getCollection("updateRemoveSample"); collection.drop();//w w w. j a v a2s .co m return collection; }
From source file:org.elasticsearch.river.mongodb.RiverMongoDBTestAbstract.java
License:Apache License
private void initMongoInstances(ExecutableType type) throws Exception { logger.debug("*** initMongoInstances(" + type + ") ***"); CommandResult cr;//from w ww . j a va 2 s .com Settings rsSettings = settings.getByPrefix(type.configKey + '.'); int[] ports; if (rsSettings.getAsBoolean("useDynamicPorts", false)) { ports = new int[] { Network.getFreeServerPort(), Network.getFreeServerPort(), Network.getFreeServerPort() }; } else { int start = 37017 + 10 * type.ordinal(); ports = new int[] { start, start + 1, start + 2 }; } String replicaSetName = "es-test-" + type.configKey; // Create 3 mongod processes Starter<IMongodConfig, MongodExecutable, MongodProcess> starter = type.newStarter(); ImmutableList.Builder<MongoReplicaSet.Member> builder = ImmutableList.builder(); for (int i = 1; i <= 3; ++i) { Storage storage = new Storage("target/" + replicaSetName + '/' + i, replicaSetName, 20); MongoReplicaSet.Member member = new MongoReplicaSet.Member(); member.config = new MongodConfigBuilder() .version(Versions.withFeatures(new GenericVersion(rsSettings.get("version")))) .net(new de.flapdoodle.embed.mongo.config.Net(ports[i - 1], Network.localhostIsIPv6())) .replication(storage).build(); logger.trace("replSetName in config: {}", member.config.replication().getReplSetName()); member.executable = starter.prepare(member.config); member.process = member.executable.start(); member.address = new ServerAddress(Network.getLocalHost().getHostName(), member.config.net().getPort()); logger.debug("Server #" + i + ": {}", member.address); builder.add(member); } ImmutableList<MongoReplicaSet.Member> members = builder.build(); Thread.sleep(2000); MongoClientOptions mco = MongoClientOptions.builder().autoConnectRetry(true).connectTimeout(15000) .socketTimeout(60000).build(); Mongo mongo = new MongoClient(new ServerAddress(Network.getLocalHost().getHostName(), ports[0]), mco); DB mongoAdminDB = mongo.getDB(ADMIN_DATABASE_NAME); cr = mongoAdminDB.command(new BasicDBObject("isMaster", 1)); logger.debug("isMaster: " + cr); // Initialize replica set cr = mongoAdminDB.command(new BasicDBObject("replSetInitiate", (DBObject) JSON.parse("{'_id': '" + replicaSetName + "', 'members': [" + "{'_id': 0, 'host': '" + members.get(0).address.getHost() + ':' + members.get(0).address.getPort() + "'}, " + "{'_id': 1, 'host': '" + members.get(1).address.getHost() + ':' + members.get(1).address.getPort() + "'}, " + "{'_id': 2, 'host': '" + members.get(2).address.getHost() + ':' + members.get(2).address.getPort() + "', 'arbiterOnly' : true}]} }"))); logger.debug("replSetInitiate result: " + cr); Thread.sleep(5000); cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1)); logger.trace("replSetGetStatus result: {}", cr); // Check replica set status before to proceed while (!isReplicaSetStarted(cr)) { logger.debug("Waiting 3 seconds for replicaset to change status..."); Thread.sleep(3000); cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1)); // logger.debug("replSetGetStatus: " + cr); } mongo.close(); mongo = null; // Initialize a new client using all instances. List<ServerAddress> mongoServers = new ArrayList<ServerAddress>(); for (MongoReplicaSet.Member member : members) { mongoServers.add(member.address); } mongo = new MongoClient(mongoServers, mco); Assert.assertNotNull(mongo); mongo.setReadPreference(ReadPreference.secondaryPreferred()); mongo.setWriteConcern(WriteConcern.REPLICAS_SAFE); replicaSets.put(type, new MongoReplicaSet(type, rsSettings.get("version"), mongo, mongoAdminDB, members)); }
From source file:org.eobjects.analyzer.connection.MongoDbDatastore.java
License:Open Source License
@Override protected UsageAwareDatastoreConnection<UpdateableDataContext> createDatastoreConnection() { try {/*from w w w . j a v a 2 s. c o m*/ Mongo mongo = new Mongo(_hostname, _port); DB mongoDb = mongo.getDB(_databaseName); if (_username != null && _password != null) { boolean authenticated = mongoDb.authenticate(_username, _password); if (!authenticated) { logger.warn("Autheticate returned false!"); } } final UpdateableDataContext dataContext; if (_tableDefs == null || _tableDefs.length == 0) { dataContext = new MongoDbDataContext(mongoDb); } else { dataContext = new MongoDbDataContext(mongoDb, _tableDefs); } return new UpdateableDatastoreConnectionImpl<UpdateableDataContext>(dataContext, this); } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new IllegalStateException("Failed to connect to MongoDB instance: " + e.getMessage(), e); } }
From source file:org.eobjects.analyzer.storage.MongoDbStorageProvider.java
License:Open Source License
@Override public RowAnnotationFactory createRowAnnotationFactory() { try {/*w w w. j a v a2 s .c o m*/ Mongo mongo = new Mongo(); DB db = mongo.getDB("analyzerbeans"); String name = "rowannotationfactory" + id.getAndIncrement(); DBCollection collection = db.createCollection(name, null); // drop the collection in case it already exists collection.drop(); collection = db.createCollection(name, null); return new MongoDbRowAnnotationFactory(collection); } catch (Exception e) { throw new IllegalStateException(e); } }