当前位置: 首页>>代码示例>>Java>>正文


Java CreateCollectionOptions类代码示例

本文整理汇总了Java中com.mongodb.client.model.CreateCollectionOptions的典型用法代码示例。如果您正苦于以下问题:Java CreateCollectionOptions类的具体用法?Java CreateCollectionOptions怎么用?Java CreateCollectionOptions使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


CreateCollectionOptions类属于com.mongodb.client.model包,在下文中一共展示了CreateCollectionOptions类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: testNoRecords

import com.mongodb.client.model.CreateCollectionOptions; //导入依赖的package包/类
@Test
public void testNoRecords() throws Exception {
    assertEquals(0, cappedTestCollection.count());
    MockEndpoint mock = getMockEndpoint("mock:test");
    mock.expectedMessageCount(0);
    //BasicDBObjectBuilder.start().add("capped", true).add("size", 1000000000).add("max", 1000).get()
    // create a capped collection with max = 1000
    CreateCollectionOptions collectionOptions = new CreateCollectionOptions()
            .capped(true)
            .sizeInBytes(1000000000)
            .maxDocuments(1000);
    db.createCollection(cappedTestCollectionName,
            collectionOptions);
    cappedTestCollection = db.getCollection(cappedTestCollectionName, BasicDBObject.class);
    assertEquals(0, cappedTestCollection.count());

    addTestRoutes();
    context.startRoute("tailableCursorConsumer1");
    Thread.sleep(1000);
    mock.assertIsSatisfied();
    context.stopRoute("tailableCursorConsumer1");

}
 
开发者ID:HydAu,项目名称:Camel,代码行数:24,代码来源:MongoDbTailableCursorConsumerTest.java

示例2: testThousandRecordsWithRouteId

import com.mongodb.client.model.CreateCollectionOptions; //导入依赖的package包/类
private void testThousandRecordsWithRouteId(String routeId) throws Exception {
    assertEquals(0, cappedTestCollection.count());
    MockEndpoint mock = getMockEndpoint("mock:test");
    mock.expectedMessageCount(1000);
   
    // create a capped collection with max = 1000
    //BasicDBObjectBuilder.start().add("capped", true).add("size", 1000000000).add("max", 1000).get()
    db.createCollection(cappedTestCollectionName,
            new CreateCollectionOptions()
                    .capped(true)
                    .sizeInBytes(1000000000)
                    .maxDocuments(1000));
    cappedTestCollection = db.getCollection(cappedTestCollectionName, BasicDBObject.class);
    for (int i = 0; i < 1000; i++) {
        cappedTestCollection.insertOne(new BasicDBObject("increasing", i).append("string", "value" + i));
    }
    assertEquals(1000, cappedTestCollection.count());

    addTestRoutes();
    context.startRoute(routeId);
    Thread.sleep(1000);
    mock.assertIsSatisfied();
    context.stopRoute(routeId);
}
 
开发者ID:HydAu,项目名称:Camel,代码行数:25,代码来源:MongoDbTailableCursorConsumerTest.java

示例3: checkCapped

import com.mongodb.client.model.CreateCollectionOptions; //导入依赖的package包/类
public static void checkCapped(MongoDatabase database, String collectionName, int size, int maxDocuments, boolean delete) {
	if (Lists.newArrayList(database.listCollectionNames()).contains(collectionName)) {
		log.debug("'{}' collection already exists...", collectionName);

		// Check if already capped
		Document command = new Document("collStats", collectionName);
		boolean isCapped = database.runCommand(command, ReadPreference.primary()).getBoolean("capped").booleanValue();

		if (!isCapped) {
			if (delete) {
				database.getCollection(collectionName).drop();
				database.createCollection(collectionName, new CreateCollectionOptions().capped(true).maxDocuments(maxDocuments).sizeInBytes(size));
			} else {
				log.info("'{}' is not capped, converting it...", collectionName);
				command = new Document("convertToCapped", collectionName).append("size", size).append("max", maxDocuments);
				database.runCommand(command, ReadPreference.primary());
			}
		} else {
			log.debug("'{}' collection already capped!", collectionName);
		}

	} else {
		database.createCollection(collectionName, new CreateCollectionOptions().capped(true).maxDocuments(maxDocuments).sizeInBytes(size));
	}
}
 
开发者ID:Treydone,项目名称:mandrel,代码行数:26,代码来源:MongoUtils.java

示例4: getOrCreateMongoCollection

import com.mongodb.client.model.CreateCollectionOptions; //导入依赖的package包/类
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);
    }

}
 
开发者ID:apache,项目名称:logging-log4j2,代码行数:21,代码来源:MongoDbConnection.java

示例5: process

import com.mongodb.client.model.CreateCollectionOptions; //导入依赖的package包/类
void process(final MappedClass mc, final Validation validation) {
    if (validation != null) {
        String collectionName = mc.getCollectionName();
        CommandResult result = getDB()
            .command(new BasicDBObject("collMod", collectionName)
                         .append("validator", parse(validation.value()))
                         .append("validationLevel", validation.level().getValue())
                         .append("validationAction", validation.action().getValue())
                    );

        if (!result.ok()) {
            if (result.getInt("code") == 26) {
                ValidationOptions options = new ValidationOptions()
                    .validator(parse(validation.value()))
                    .validationLevel(validation.level())
                    .validationAction(validation.action());
                getDatabase().createCollection(collectionName, new CreateCollectionOptions().validationOptions(options));
            } else {
                result.throwOnError();
            }
        }
    }
}
 
开发者ID:mongodb,项目名称:morphia,代码行数:24,代码来源:DatastoreImpl.java

示例6: EventQueue

import com.mongodb.client.model.CreateCollectionOptions; //导入依赖的package包/类
public EventQueue(MongoDatabase db, HamsterEngine engine) {
    this.db = db;
    this.engine = engine;

    boolean exists = false;
    for (String name : db.listCollectionNames()) {
        if (name.equals(COLLECTION_NAME)) {
            exists = true;
            break;
        }
    }
    if (!exists) {
        CreateCollectionOptions options = new CreateCollectionOptions();
        options.capped(true);
        options.sizeInBytes(QUEUE_SIZE);
        options.maxDocuments(300);
        db.createCollection(COLLECTION_NAME, options);
    }
    queueCollection = db.getCollection(COLLECTION_NAME);
    pid = UUID.randomUUID().toString();

    Thread queuePoller = new Thread(new Runnable() {

        @Override
        public void run() {
            tailQueue();
        }
    }, "event queue processor");
    engine.addThread(queuePoller);
    queuePoller.start();
}
 
开发者ID:KAOREND,项目名称:reactive-hamster,代码行数:32,代码来源:EventQueue.java

示例7: createCollection

import com.mongodb.client.model.CreateCollectionOptions; //导入依赖的package包/类
@Override
public Observable<Success> createCollection(final String collectionName, final CreateCollectionOptions options) {
    return RxObservables.create(Observables.observe(new Block<SingleResultCallback<Success>>() {
        @Override
        public void apply(final SingleResultCallback<Success> callback) {
            wrapped.createCollection(collectionName, options, voidToSuccessCallback(callback));
        }
    }), observableAdapter);
}
 
开发者ID:mongodb,项目名称:mongo-java-driver-rx,代码行数:10,代码来源:MongoDatabaseImpl.java

示例8: createCollection

import com.mongodb.client.model.CreateCollectionOptions; //导入依赖的package包/类
@Override
public Publisher<Success> createCollection(final String collectionName, final CreateCollectionOptions options) {
    return new ObservableToPublisher<Success>(observe(new Block<SingleResultCallback<Success>>() {
        @Override
        public void apply(final SingleResultCallback<Success> callback) {
            wrapped.createCollection(collectionName, options, voidToSuccessCallback(callback));
        }
    }));
}
 
开发者ID:mongodb,项目名称:mongo-java-driver-reactivestreams,代码行数:10,代码来源:MongoDatabaseImpl.java

示例9: testBypassDocumentValidation

import com.mongodb.client.model.CreateCollectionOptions; //导入依赖的package包/类
@Test
public void testBypassDocumentValidation() {
    checkMinServerVersion(3.2);
    getDs().save(asList(new User("john doe", new Date()), new User("John Doe", new Date())));

    MongoDatabase database = getMongoClient().getDatabase(TEST_DB_NAME);
    database.getCollection("out_users").drop();
    database.createCollection("out_users", new CreateCollectionOptions()
        .validationOptions(new ValidationOptions()
                               .validator(Document.parse("{ age : { gte : 13 } }"))));

    try {
        getDs()
            .createAggregation(User.class)
            .match(getDs().find(User.class).field("name").equal("john doe"))
            .out("out_users", User.class);
        fail("Document validation should have complained.");
    } catch (MongoCommandException e) {
        // expected
    }

    getDs()
        .createAggregation(User.class)
        .match(getDs().find(User.class).field("name").equal("john doe"))
        .out("out_users", User.class, builder()
            .bypassDocumentValidation(true)
            .build());

    Assert.assertEquals(1, getAds().find("out_users", User.class).count());
}
 
开发者ID:mongodb,项目名称:morphia,代码行数:31,代码来源:AggregationTest.java

示例10: testBypassDocumentValidation

import com.mongodb.client.model.CreateCollectionOptions; //导入依赖的package包/类
@Test
public void testBypassDocumentValidation() {
    checkMinServerVersion(3.4);
    getDs().save(asList(new Book("The Banquet", "Dante", 2),
                        new Book("Divine Comedy", "Dante", 1),
                        new Book("Eclogues", "Dante", 2),
                        new Book("The Odyssey", "Homer", 10),
                        new Book("Iliad", "Homer", 10)));

    Document validator = Document.parse("{ count : { $gt : '10' } }");
    ValidationOptions validationOptions = new ValidationOptions()
        .validator(validator)
        .validationLevel(ValidationLevel.STRICT)
        .validationAction(ValidationAction.ERROR);
    MongoDatabase database = getMongoClient().getDatabase(TEST_DB_NAME);
    database.getCollection("counts").drop();
    database.createCollection("counts", new CreateCollectionOptions().validationOptions(validationOptions));


    final String map = "function () { emit(this.author, 1); return; }";
    final String reduce = "function (key, values) { return values.length }";

    MapReduceOptions<CountResult> options = new MapReduceOptions<CountResult>()
        .query(getDs().find(Book.class))
        .resultType(CountResult.class)
        .outputType(OutputType.REPLACE)
        .map(map)
        .reduce(reduce);
    try {
        getDs().mapReduce(options);
        fail("Document validation should have complained.");
    } catch (MongoCommandException e) {
        // expected
    }

    getDs().mapReduce(options.bypassDocumentValidation(true));
    Assert.assertEquals(2, count(getDs().find(CountResult.class).iterator()));
}
 
开发者ID:mongodb,项目名称:morphia,代码行数:39,代码来源:TestMapreduce.java

示例11: addValidation

import com.mongodb.client.model.CreateCollectionOptions; //导入依赖的package包/类
private MongoDatabase addValidation(final Document validator, final String collectionName) {
    ValidationOptions options = new ValidationOptions()
        .validator(validator)
        .validationLevel(ValidationLevel.MODERATE)
        .validationAction(ValidationAction.ERROR);
    MongoDatabase database = getMongoClient().getDatabase(TEST_DB_NAME);
    database.getCollection(collectionName).drop();
    database.createCollection(collectionName, new CreateCollectionOptions().validationOptions(options));
    return database;
}
 
开发者ID:mongodb,项目名称:morphia,代码行数:11,代码来源:TestDocumentValidation.java

示例12: createCollection

import com.mongodb.client.model.CreateCollectionOptions; //导入依赖的package包/类
@Override
public void createCollection(String collectionName, CreateCollectionOptions createCollectionOptions)
{
    database.createCollection(collectionName, createCollectionOptions);
}
 
开发者ID:dd00f,项目名称:ibm-performance-monitor,代码行数:6,代码来源:ProfiledMongoDatabase.java

示例13: testMultipleBursts

import com.mongodb.client.model.CreateCollectionOptions; //导入依赖的package包/类
@Test
public void testMultipleBursts() throws Exception {
    assertEquals(0, cappedTestCollection.count());
    MockEndpoint mock = getMockEndpoint("mock:test");
    mock.expectedMessageCount(5000);
    //BasicDBObjectBuilder.start().add("capped", true).add("size", 1000000000).add("max", 1000).get()
    // create a capped collection with max = 1000
    CreateCollectionOptions createCollectionOptions = new CreateCollectionOptions()
            .capped(true)
            .sizeInBytes(1000000000)
            .maxDocuments(1000);
    db.createCollection(cappedTestCollectionName,
            createCollectionOptions);
    cappedTestCollection = db.getCollection(cappedTestCollectionName, BasicDBObject.class);
    addTestRoutes();
    context.startRoute("tailableCursorConsumer1");
    
    // pump 5 bursts of 1000 records each with 500ms pause between burst and burst
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < 5000; i++) {
                if (i % 1000 == 0) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        return;
                    }
                }
                cappedTestCollection.insertOne(new BasicDBObject("increasing", i).append("string", "value" + i));
            }
            
        }
    });
    
    // start the data pumping
    t.start();
    // before we assert, wait for the data pumping to end
    t.join();
    
    mock.assertIsSatisfied();
    context.stopRoute("tailableCursorConsumer1");

}
 
开发者ID:HydAu,项目名称:Camel,代码行数:45,代码来源:MongoDbTailableCursorConsumerTest.java

示例14: testHundredThousandRecords

import com.mongodb.client.model.CreateCollectionOptions; //导入依赖的package包/类
@Test
public void testHundredThousandRecords() throws Exception {
    assertEquals(0, cappedTestCollection.count());
    final MockEndpoint mock = getMockEndpoint("mock:test");
    mock.expectedMessageCount(1000);
   
    // create a capped collection with max = 1000
    //BasicDBObjectBuilder.start().add("capped", true).add("size", 1000000000).add("max", 1000).get())
    db.createCollection(cappedTestCollectionName,
            new CreateCollectionOptions()
                    .capped(true)
                    .sizeInBytes(1000000000)
                    .maxDocuments(1000));
    cappedTestCollection = db.getCollection(cappedTestCollectionName, BasicDBObject.class);
    addTestRoutes();
    context.startRoute("tailableCursorConsumer1");
    
    // continuous pump of 100000 records, asserting incrementally to reduce overhead on the mock endpoint
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 1; i <= 100000; i++) {
                cappedTestCollection.insertOne(new BasicDBObject("increasing", i).append("string", "value" + i));
                
                // incrementally assert, as the mock endpoint stores all messages and otherwise the test would be sluggish
                if (i % 1000 == 0) {
                    try {
                        MongoDbTailableCursorConsumerTest.this.assertAndResetMockEndpoint(mock);
                    } catch (Exception e) {
                        return;
                    }
                }       
            }
        }
    });
    
    // start the data pumping
    t.start();
    // before we stop the route, wait for the data pumping to end
    t.join();
    
    context.stopRoute("tailableCursorConsumer1");

}
 
开发者ID:HydAu,项目名称:Camel,代码行数:45,代码来源:MongoDbTailableCursorConsumerTest.java

示例15: testPersistentTailTrack

import com.mongodb.client.model.CreateCollectionOptions; //导入依赖的package包/类
@Test
public void testPersistentTailTrack() throws Exception {
    assertEquals(0, cappedTestCollection.count());
    final MockEndpoint mock = getMockEndpoint("mock:test");
    
    // drop the tracking collection
    db.getCollection(MongoDbTailTrackingConfig.DEFAULT_COLLECTION).drop();
    // create a capped collection with max = 1000
    // BasicDBObjectBuilder.start().add("capped", true).add("size", 1000000000).add("max", 1000).get()
    db.createCollection(cappedTestCollectionName,
            new CreateCollectionOptions()
                    .capped(true)
                    .sizeInBytes(1000000000)
                    .maxDocuments(1000));
    cappedTestCollection = db.getCollection(cappedTestCollectionName, BasicDBObject.class);
    cappedTestCollection.createIndex(new BasicDBObject("increasing", 1));

    addTestRoutes();
    context.startRoute("tailableCursorConsumer2");
    
    mock.expectedMessageCount(300);
    // pump 300 records
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 1; i <= 300; i++) {
                cappedTestCollection.insertOne(new BasicDBObject("increasing", i).append("string", "value" + i));
            }
        }
    });
    
    // start the data pumping
    t.start();
    // before we continue wait for the data pump to end
    t.join();
    mock.assertIsSatisfied();
    mock.reset();
    context.stopRoute("tailableCursorConsumer2");
    while (context.getRouteStatus("tailableCursorConsumer2") != ServiceStatus.Stopped) { }
    context.startRoute("tailableCursorConsumer2");
    
    // expect 300 messages and not 600
    mock.expectedMessageCount(300);
    // pump 300 records
    t = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 301; i <= 600; i++) {
                cappedTestCollection.insertOne(new BasicDBObject("increasing", i).append("string", "value" + i));
            }
        }
    });
    // start the data pumping
    t.start();
    // before we continue wait for the data pump to end
    t.join();
    mock.assertIsSatisfied();
    
    // check that the first message received in this second batch corresponds to increasing=301
    Object firstBody = mock.getExchanges().get(0).getIn().getBody();
    assertTrue(firstBody instanceof DBObject);
    assertEquals(301, ((DBObject) firstBody).get("increasing"));
    
    // check that the lastVal is persisted at the right time: check before and after stopping the route
    assertEquals(300, db.getCollection(MongoDbTailTrackingConfig.DEFAULT_COLLECTION).find(new BasicDBObject("persistentId", "darwin")).first().get("lastTrackingValue"));
    // stop the route and verify the last value has been updated
    context.stopRoute("tailableCursorConsumer2");
    while (context.getRouteStatus("tailableCursorConsumer2") != ServiceStatus.Stopped) { }
    assertEquals(600, db.getCollection(MongoDbTailTrackingConfig.DEFAULT_COLLECTION).find(new BasicDBObject("persistentId", "darwin")).first().get("lastTrackingValue"));

}
 
开发者ID:HydAu,项目名称:Camel,代码行数:72,代码来源:MongoDbTailableCursorConsumerTest.java


注:本文中的com.mongodb.client.model.CreateCollectionOptions类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。