Java Code Examples for com.mongodb.client.MongoDatabase#createCollection()

The following examples show how to use com.mongodb.client.MongoDatabase#createCollection() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: VaultConfigMongoTests.java    From spring-cloud-vault with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldConnectUsingDataSource() {

	MongoDatabase mongoDatabase = this.mongoClient.getDatabase("admin");

	List<Document> collections = mongoDatabase.listCollections()
			.into(new ArrayList<>());

	for (Document collection : collections) {
		if (collection.getString("name").equals("hello")) {
			mongoDatabase.getCollection(collection.getString("name")).drop();
		}
	}

	mongoDatabase.createCollection("hello");
}
 
Example 2
Source File: MongoDb3Connection.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private static MongoCollection<Document> getOrCreateMongoCollection(final MongoDatabase database,
        final String collectionName, final boolean isCapped, final Integer sizeInBytes) {
    try {
        LOGGER.debug("Gettting collection '{}'...", collectionName);
        // throws IllegalArgumentException if collectionName is invalid
        return database.getCollection(collectionName);
    } catch (final IllegalStateException e) {
        LOGGER.debug("Collection '{}' does not exist.", collectionName);
        final CreateCollectionOptions options = new CreateCollectionOptions()
        // @formatter:off
                .capped(isCapped)
                .sizeInBytes(sizeInBytes);
        // @formatter:on
        LOGGER.debug("Creating collection {} (capped = {}, sizeInBytes = {})", collectionName, isCapped,
                sizeInBytes);
        database.createCollection(collectionName, options);
        return database.getCollection(collectionName);
    }

}
 
Example 3
Source File: MongoDb4Connection.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private static MongoCollection<Document> getOrCreateMongoCollection(final MongoDatabase database,
        final String collectionName, final boolean isCapped, final Integer sizeInBytes) {
    try {
        LOGGER.debug("Gettting collection '{}'...", collectionName);
        // throws IllegalArgumentException if collectionName is invalid
        final MongoCollection<Document> found = database.getCollection(collectionName);
        LOGGER.debug("Got collection {}", found);
        return found;
    } catch (final IllegalStateException e) {
        LOGGER.debug("Collection '{}' does not exist.", collectionName);
        final CreateCollectionOptions options = new CreateCollectionOptions().capped(isCapped)
                .sizeInBytes(sizeInBytes);
        LOGGER.debug("Creating collection '{}' with options {}...", collectionName, options);
        database.createCollection(collectionName, options);
        LOGGER.debug("Created collection.");
        final MongoCollection<Document> created = database.getCollection(collectionName);
        LOGGER.debug("Got created collection {}", created);
        return created;
    }

}
 
Example 4
Source File: MongoAdminService.java    From cloudfoundry-service-broker with Apache License 2.0 6 votes vote down vote up
public MongoDatabase createDatabase(String databaseName) throws MongoServiceException {
	try {
		addDbOwnerRole(databaseName);
		
		MongoDatabase db = client.getDatabase(databaseName);
		db.createCollection("foo");
		// save into a collection to force DB creation.
		MongoCollection<Document> col = db.getCollection("foo");
		Document document = new Document("foo", "bar");
		
		col.insertOne(document);
		// drop the collection so the db is empty
		// TODO: figure out how to clean the db in a different "transaction" so the create is flushed
		// currently dropping the column is preventing the database from being created. 
		// col.drop();

		return db;
	} catch (MongoException e) {
		// try to clean up and fail
		try {
			deleteDatabase(databaseName);
		} catch (MongoServiceException ignore) {}
		throw handleException(e);
	}
}
 
Example 5
Source File: MongoDBLookupProcessorIT.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  MongoDatabase db = mongo.getDatabase(DATABASE_NAME);
  db.createCollection(TEST_COLLECTION);
  testCollection = db.getCollection(TEST_COLLECTION);
  testCollection.insertOne(
      new Document()
          .append("id", 1)
          .append("name", "StreamSets")
          .append("location", "Fan Francisco")
  );
  testCollection.insertOne(
      new Document()
          .append("id", 2)
          .append("name", "MongoDB")
          .append("location", "Palo Alto")
  );
  builder = new MongoDBProcessorBuilder();
  builder.connectionString("mongodb://" + mongoContainer.getContainerIpAddress() + ":" + mongoContainer.getMappedPort(MongoDBConfig.MONGO_DEFAULT_PORT));
  builder.database(DATABASE_NAME);
  builder.collection(TEST_COLLECTION);
}
 
Example 6
Source File: MongoDBOplogSourceIT.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Before
public void createCollection() throws Exception {
  MongoDatabase db = mongoClient.getDatabase(DATABASE);
  testCollectionName = name.getMethodName();
  db.createCollection(testCollectionName);
  final long currentTime = System.currentTimeMillis();
  //To make sure that oplog is read on each method after we created the above collection.
  //We let this current second pass, before we get the initial timestamp seconds.
  Awaitility.await().untilTrue(new AtomicBoolean((System.currentTimeMillis() - currentTime) > 1000));
  //So we can skip old oplogs and just start with whatever this test is producing
  initialTs = getInitialTsFromCurrentTime();
  testDocuments = mongoClient.getDatabase(DATABASE).getCollection(testCollectionName);
  mongoCursorFindIterable = mongoClient.getDatabase("local").getCollection(OPLOG_COLLECTION)
      .find()
      //As the collection is a capped collection we use Tailable cursor which will return results in natural order in this case
      //based on ts timestamp field.
      //Tailable Await does not return and blocks, so we are using tailable.
      .cursorType(CursorType.Tailable);
}
 
Example 7
Source File: CamelSourceMongoDBITCase.java    From camel-kafka-connector with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setUp() {
    mongoClient = mongoDBService.getClient();

    MongoDatabase database = mongoClient.getDatabase("testDatabase");

    /*
     The consume operation needs taliable cursors which require capped
     collections
     */
    CreateCollectionOptions options = new CreateCollectionOptions();
    options.capped(true);
    options.sizeInBytes(1024 * 1024);

    database.createCollection("testCollection", options);

    MongoCollection<Document> collection = database.getCollection("testCollection");

    List<Document> documents = new ArrayList<>(expect);
    for (int i = 0; i < expect; i++) {
        Document doc = new Document();

        doc.append("name", "test");
        doc.append("value", "value " + i);

        documents.add(doc);
    }

    collection.insertMany(documents);
}
 
Example 8
Source File: CaseController.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/mongodb")
public String mongoDBCase() {
    try (MongoClient mongoClient = new MongoClient(host, port)) {
        MongoDatabase db = mongoClient.getDatabase("test-database");
        // CreateCollectionOperation
        db.createCollection("testCollection");

        MongoCollection<Document> collection = db.getCollection("testCollection");
        Document document = Document.parse("{id: 1, name: \"test\"}");
        // MixedBulkWriteOperation
        collection.insertOne(document);

        // FindOperation
        FindIterable<Document> findIterable = collection.find(eq("name", "org"));
        findIterable.first();

        // MixedBulkWriteOperation
        collection.updateOne(eq("name", "org"), BsonDocument.parse("{ $set : { \"name\": \"testA\"} }"));

        // FindOperation
        findIterable = collection.find(eq("name", "testA"));
        findIterable.first();

        // MixedBulkWriteOperation
        collection.deleteOne(eq("id", "1"));

        // DropDatabaseOperation
        mongoClient.dropDatabase("test-database");
    }
    return "success";
}
 
Example 9
Source File: LoadAuthors.java    From Java-Data-Analysis with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    MongoClient client = new MongoClient("localhost", 27017);
    MongoDatabase library = client.getDatabase("library");
    MongoCollection authors = library.getCollection("authors");
    
    authors.drop();
    library.createCollection("authors");
    load(authors);
}
 
Example 10
Source File: LoadBooks.java    From Java-Data-Analysis with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    MongoClient client = new MongoClient("localhost", 27017);
    MongoDatabase library = client.getDatabase("library");
    MongoCollection books = library.getCollection("books");
    
    books.drop();
    library.createCollection("books");
    load(books);
}
 
Example 11
Source File: MongoDBTargetIT.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  MongoDatabase db = mongo.getDatabase(DATABASE_NAME);
  db.createCollection(TEST_WRITE_COLLECTION);
  db.createCollection(UNIQUE_KEY_EXCEPTION_COLLECTION);
  testWriteCollection = db.getCollection(TEST_WRITE_COLLECTION);
  testWriteCollection.createIndex(Indexes.text("name"), new IndexOptions().unique(true));
}
 
Example 12
Source File: TestDocumentValidation.java    From morphia with Apache License 2.0 5 votes vote down vote up
private MongoDatabase addValidation(final Document validator) {
    ValidationOptions options = new ValidationOptions()
                                    .validator(validator)
                                    .validationLevel(ValidationLevel.MODERATE)
                                    .validationAction(ValidationAction.ERROR);
    MongoDatabase database = getMongoClient().getDatabase(TEST_DB_NAME);
    database.getCollection("validation").drop();
    database.createCollection("validation", new CreateCollectionOptions().validationOptions(options));
    return database;
}
 
Example 13
Source File: MongodbSourceUriTaskTest.java    From kafka-connect-mongodb with Apache License 2.0 4 votes vote down vote up
@Override
    public void setUp() {
        offsets = new HashMap<>();
        totalWrittenDocuments = 0;
        try {
            super.setUp();
            mongodStarter = MongodStarter.getDefaultInstance();
            mongodConfig = new MongodConfigBuilder()
                    .version(Version.Main.V3_2)
                    .replication(new Storage(REPLICATION_PATH, "rs0", 1024))
                    .net(new Net(12345, Network.localhostIsIPv6()))
                    .build();
            mongodExecutable = mongodStarter.prepare(mongodConfig);
            mongod = mongodExecutable.start();
            mongoClient = new MongoClient(new ServerAddress("localhost", 12345));
            MongoDatabase adminDatabase = mongoClient.getDatabase("admin");

            BasicDBObject replicaSetSetting = new BasicDBObject();
            replicaSetSetting.put("_id", "rs0");
            BasicDBList members = new BasicDBList();
            DBObject host = new BasicDBObject();
            host.put("_id", 0);
            host.put("host", "127.0.0.1:12345");
            members.add(host);
            replicaSetSetting.put("members", members);
            adminDatabase.runCommand(new BasicDBObject("isMaster", 1));
            adminDatabase.runCommand(new BasicDBObject("replSetInitiate", replicaSetSetting));
            MongoDatabase db = mongoClient.getDatabase("mydb");
            db.createCollection("test1");
            db.createCollection("test2");
            db.createCollection("test3");
        } catch (Exception e) {
//                Assert.assertTrue(false);
        }

        task = new MongodbSourceTask();

        offsetStorageReader = PowerMock.createMock(OffsetStorageReader.class);
        context = PowerMock.createMock(SourceTaskContext.class);
        task.initialize(context);

        sourceProperties = new HashMap<>();
        sourceProperties.put("uri", "mongodb://localhost:12345");
        sourceProperties.put("batch.size", Integer.toString(100));
        sourceProperties.put("schema.name", "schema");
        sourceProperties.put("topic.prefix", "prefix");
        sourceProperties.put("databases", "mydb.test1,mydb.test2,mydb.test3");

    }
 
Example 14
Source File: MongodbSourceTaskTest.java    From kafka-connect-mongodb with Apache License 2.0 4 votes vote down vote up
@Override
    public void setUp() {
        offsets = new HashMap<>();
        totalWrittenDocuments = 0;
        try {
            super.setUp();
            mongodStarter = MongodStarter.getDefaultInstance();
            mongodConfig = new MongodConfigBuilder()
                    .version(Version.Main.V3_2)
                    .replication(new Storage(REPLICATION_PATH, "rs0", 1024))
                    .net(new Net(12345, Network.localhostIsIPv6()))
                    .build();
            mongodExecutable = mongodStarter.prepare(mongodConfig);
            mongod = mongodExecutable.start();
            mongoClient = new MongoClient(new ServerAddress("localhost", 12345));
            MongoDatabase adminDatabase = mongoClient.getDatabase("admin");

            BasicDBObject replicaSetSetting = new BasicDBObject();
            replicaSetSetting.put("_id", "rs0");
            BasicDBList members = new BasicDBList();
            DBObject host = new BasicDBObject();
            host.put("_id", 0);
            host.put("host", "127.0.0.1:12345");
            members.add(host);
            replicaSetSetting.put("members", members);
            adminDatabase.runCommand(new BasicDBObject("isMaster", 1));
            adminDatabase.runCommand(new BasicDBObject("replSetInitiate", replicaSetSetting));
            MongoDatabase db = mongoClient.getDatabase("mydb");
            db.createCollection("test1");
            db.createCollection("test2");
            db.createCollection("test3");
        } catch (Exception e) {
//                Assert.assertTrue(false);
        }

        task = new MongodbSourceTask();

        offsetStorageReader = PowerMock.createMock(OffsetStorageReader.class);
        context = PowerMock.createMock(SourceTaskContext.class);
        task.initialize(context);

        sourceProperties = new HashMap<>();
        sourceProperties.put("host", "localhost");
        sourceProperties.put("port", Integer.toString(12345));
        sourceProperties.put("batch.size", Integer.toString(100));
        sourceProperties.put("schema.name", "schema");
        sourceProperties.put("topic.prefix", "prefix");
        sourceProperties.put("databases", "mydb.test1,mydb.test2,mydb.test3");

    }
 
Example 15
Source File: MongoDbClient.java    From javase with MIT License 4 votes vote down vote up
public static void main( String args[] ) {
	
      try{
		
         // To connect to mongodb server
         MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
			
         // Now connect to your databases
         MongoDatabase db = mongoClient.getDatabase("test"); 
         //DB db = mongoClient.getDB( "test" );
         System.out.println("Connect to database successfully");
         //boolean auth = db.authenticate(myUserName, myPassword);
         //System.out.println("Authentication: "+auth);
		
         //DBCollection coll = db.createCollection("mycol", null);
         if (db.getCollection("mycol") != null) {
        	 db.getCollection("mycol").drop();
         }
         db.createCollection("mycol");
         
         System.out.println("Collection created successfully");
         
         // /*DBCollection*/ coll = db.getCollection("mycol");
         MongoCollection<Document> coll = db.getCollection("mycol");
         System.out.println("Collection mycol selected successfully");
			
//         BasicDBObject doc = new BasicDBObject("title", "MongoDB").
//            append("description", "database").
//            append("likes", 100).
//            append("url", "http://www.tutorialspoint.com/mongodb/").
//            append("by", "tutorials point");
         Document doc = new Document("title", "MongoDB").
               append("description", "database").
               append("likes", 100).
               append("url", "http://www.tutorialspoint.com/mongodb/").
               append("by", "tutorials point"); 
				
         //coll.insert(doc);
         coll.insertOne(doc);
         System.out.println("Document inserted successfully");
         
         
         /*DBCollection*/ coll = db.getCollection("mycol");
         System.out.println("Collection mycol selected successfully");
			
         //DBCursor cursor = coll.find();
         FindIterable<Document> iterableFind = coll.find();
         MongoCursor<Document> cursor = iterableFind.iterator();
         int i = 1;
			
         while (cursor.hasNext()) { 
            System.out.println("Inserted Document: "+i); 
            System.out.println(cursor.next()); 
            i++;
         }
         
         mongoClient.close();
      }catch(Exception e){
         System.err.println( e.getClass().getName() + ": " + e.getMessage() );
      }
   }
 
Example 16
Source File: MongoDbClient.java    From javase with MIT License 4 votes vote down vote up
public static void main( String args[] ) {
	
      try{
		
         // To connect to mongodb server
         MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
			
         // Now connect to your databases
         MongoDatabase db = mongoClient.getDatabase("test"); 
         //DB db = mongoClient.getDB( "test" );
         System.out.println("Connect to database successfully");
         //boolean auth = db.authenticate(myUserName, myPassword);
         //System.out.println("Authentication: "+auth);
		
         //DBCollection coll = db.createCollection("mycol", null);
         if (db.getCollection("mycol") != null) {
        	 db.getCollection("mycol").drop();
         }
         db.createCollection("mycol");
         
         System.out.println("Collection created successfully");
         
         // /*DBCollection*/ coll = db.getCollection("mycol");
         MongoCollection<Document> coll = db.getCollection("mycol");
         System.out.println("Collection mycol selected successfully");
			
//         BasicDBObject doc = new BasicDBObject("title", "MongoDB").
//            append("description", "database").
//            append("likes", 100).
//            append("url", "http://www.tutorialspoint.com/mongodb/").
//            append("by", "tutorials point");
         Document doc = new Document("title", "MongoDB").
               append("description", "database").
               append("likes", 100).
               append("url", "http://www.tutorialspoint.com/mongodb/").
               append("by", "tutorials point"); 
				
         //coll.insert(doc);
         coll.insertOne(doc);
         System.out.println("Document inserted successfully: " + doc.toJson());
         
         
         /*DBCollection*/ coll = db.getCollection("mycol");
         System.out.println("Collection mycol selected successfully");
			
         //DBCursor cursor = coll.find();
         FindIterable<Document> iterableFind = coll.find();
         MongoCursor<Document> cursor = iterableFind.iterator();
         int i = 1;
			
         while (cursor.hasNext()) { 
            System.out.println("Inserted Document: "+i); 
            System.out.println(cursor.next()); 
            i++;
         }
         
         mongoClient.close();
      }catch(Exception e){
         System.err.println( e.getClass().getName() + ": " + e.getMessage() );
      }
   }
 
Example 17
Source File: MongoSourceConnectorTest.java    From mongo-kafka with Apache License 2.0 4 votes vote down vote up
private MongoCollection<Document> getAndCreateCollection() {
  MongoDatabase database = getDatabaseWithPostfix();
  database.createCollection("coll");
  return database.getCollection("coll");
}