Search in sources :

Example 1 with CreateCollectionOptions

use of com.mongodb.client.model.CreateCollectionOptions in project morphia by mongodb.

the class DatastoreImpl method process.

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();
            }
        }
    }
}
Also used : BasicDBObject(com.mongodb.BasicDBObject) CreateCollectionOptions(com.mongodb.client.model.CreateCollectionOptions) ValidationOptions(com.mongodb.client.model.ValidationOptions) CommandResult(com.mongodb.CommandResult)

Example 2 with CreateCollectionOptions

use of com.mongodb.client.model.CreateCollectionOptions in project morphia by mongodb.

the class TestDocumentValidation method addValidation.

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;
}
Also used : CreateCollectionOptions(com.mongodb.client.model.CreateCollectionOptions) ValidationOptions(com.mongodb.client.model.ValidationOptions) MongoDatabase(com.mongodb.client.MongoDatabase)

Example 3 with CreateCollectionOptions

use of com.mongodb.client.model.CreateCollectionOptions in project morphia by mongodb.

the class TestMapreduce method testBypassDocumentValidation.

@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()));
}
Also used : MongoCommandException(com.mongodb.MongoCommandException) Book(org.mongodb.morphia.aggregation.AggregationTest.Book) CreateCollectionOptions(com.mongodb.client.model.CreateCollectionOptions) Document(org.bson.Document) ValidationOptions(com.mongodb.client.model.ValidationOptions) CountResult(org.mongodb.morphia.aggregation.AggregationTest.CountResult) MongoDatabase(com.mongodb.client.MongoDatabase) Test(org.junit.Test)

Example 4 with CreateCollectionOptions

use of com.mongodb.client.model.CreateCollectionOptions in project mongo-java-driver by mongodb.

the class QuickTourAdmin method main.

/**
     * Run this main method to see the output of this quick example.
     *
     * @param args takes an optional single argument for the connection string
     */
public static void main(final String[] args) {
    MongoClient mongoClient;
    if (args.length == 0) {
        // connect to the local database server
        mongoClient = new MongoClient();
    } else {
        mongoClient = new MongoClient(new MongoClientURI(args[0]));
    }
    // get handle to "mydb" database
    MongoDatabase database = mongoClient.getDatabase("mydb");
    database.drop();
    // get a handle to the "test" collection
    MongoCollection<Document> collection = database.getCollection("test");
    // drop all the data in it
    collection.drop();
    // getting a list of databases
    for (String name : mongoClient.listDatabaseNames()) {
        System.out.println(name);
    }
    // drop a database
    mongoClient.getDatabase("databaseToBeDropped").drop();
    // create a collection
    database.createCollection("cappedCollection", new CreateCollectionOptions().capped(true).sizeInBytes(0x100000));
    for (String name : database.listCollectionNames()) {
        System.out.println(name);
    }
    // drop a collection:
    collection.drop();
    // create an ascending index on the "i" field
    collection.createIndex(Indexes.ascending("i"));
    // list the indexes on the collection
    for (final Document index : collection.listIndexes()) {
        System.out.println(index.toJson());
    }
    // create a text index on the "content" field
    collection.createIndex(Indexes.text("content"));
    collection.insertOne(new Document("_id", 0).append("content", "textual content"));
    collection.insertOne(new Document("_id", 1).append("content", "additional content"));
    collection.insertOne(new Document("_id", 2).append("content", "irrelevant content"));
    // Find using the text index
    long matchCount = collection.count(text("textual content -irrelevant"));
    System.out.println("Text search matches: " + matchCount);
    // Find using the $language operator
    Bson textSearch = text("textual content -irrelevant", new TextSearchOptions().language("english"));
    matchCount = collection.count(textSearch);
    System.out.println("Text search matches (english): " + matchCount);
    // Find the highest scoring match
    Document projection = new Document("score", new Document("$meta", "textScore"));
    Document myDoc = collection.find(textSearch).projection(projection).first();
    System.out.println("Highest scoring document: " + myDoc.toJson());
    // Run a command
    Document buildInfo = database.runCommand(new Document("buildInfo", 1));
    System.out.println(buildInfo);
    // release resources
    database.drop();
    mongoClient.close();
}
Also used : MongoClient(com.mongodb.MongoClient) MongoClientURI(com.mongodb.MongoClientURI) CreateCollectionOptions(com.mongodb.client.model.CreateCollectionOptions) TextSearchOptions(com.mongodb.client.model.TextSearchOptions) Document(org.bson.Document) MongoDatabase(com.mongodb.client.MongoDatabase) Bson(org.bson.conversions.Bson)

Example 5 with CreateCollectionOptions

use of com.mongodb.client.model.CreateCollectionOptions in project camel by apache.

the class MongoDbTailableCursorConsumerTest method testPersistentTailTrackIncreasingDateField.

@Test
public void testPersistentTailTrackIncreasingDateField() throws Exception {
    assertEquals(0, cappedTestCollection.count());
    final MockEndpoint mock = getMockEndpoint("mock:test");
    final Calendar startTimestamp = Calendar.getInstance();
    // get default tracking collection
    MongoCollection<BasicDBObject> trackingCol = db.getCollection(MongoDbTailTrackingConfig.DEFAULT_COLLECTION, BasicDBObject.class);
    trackingCol.drop();
    trackingCol = db.getCollection(MongoDbTailTrackingConfig.DEFAULT_COLLECTION, BasicDBObject.class);
    // 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("tailableCursorConsumer2");
    mock.expectedMessageCount(300);
    // pump 300 records
    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            for (int i = 1; i <= 300; i++) {
                Calendar c = (Calendar) (startTimestamp.clone());
                c.add(Calendar.MINUTE, i);
                cappedTestCollection.insertOne(new BasicDBObject("increasing", c.getTime()).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();
    // ensure that the persisted lastVal is startTimestamp + 300min
    Calendar cal300 = (Calendar) startTimestamp.clone();
    cal300.add(Calendar.MINUTE, 300);
    context.stopRoute("tailableCursorConsumer2");
    assertEquals(cal300.getTime(), trackingCol.find(new BasicDBObject("persistentId", "darwin")).first().get(MongoDbTailTrackingConfig.DEFAULT_FIELD));
    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++) {
                Calendar c = (Calendar) (startTimestamp.clone());
                c.add(Calendar.MINUTE, i);
                cappedTestCollection.insertOne(new BasicDBObject("increasing", c.getTime()).append("string", "value" + i));
            }
        }
    });
    // start the data pumping
    t.start();
    // before we continue wait for the data pump to end
    t.join();
    mock.assertIsSatisfied();
    Object firstBody = mock.getExchanges().get(0).getIn().getBody();
    assertTrue(firstBody instanceof DBObject);
    Calendar cal301 = (Calendar) startTimestamp.clone();
    cal301.add(Calendar.MINUTE, 301);
    assertEquals(cal301.getTime(), ((DBObject) firstBody).get("increasing"));
    // check that the persisted lastVal after stopping the route is startTimestamp + 600min
    context.stopRoute("tailableCursorConsumer2");
    Calendar cal600 = (Calendar) startTimestamp.clone();
    cal600.add(Calendar.MINUTE, 600);
    assertEquals(cal600.getTime(), trackingCol.find(new BasicDBObject("persistentId", "darwin")).first().get(MongoDbTailTrackingConfig.DEFAULT_FIELD));
}
Also used : BasicDBObject(com.mongodb.BasicDBObject) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) Calendar(java.util.Calendar) CreateCollectionOptions(com.mongodb.client.model.CreateCollectionOptions) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) Test(org.junit.Test)

Aggregations

CreateCollectionOptions (com.mongodb.client.model.CreateCollectionOptions)38 Document (org.bson.Document)19 Test (org.junit.Test)19 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)14 ValidationOptions (com.mongodb.client.model.ValidationOptions)11 BasicDBObject (com.mongodb.BasicDBObject)8 MongoDatabase (com.mongodb.client.MongoDatabase)8 BsonDocument (org.bson.BsonDocument)5 MongoNamespace (com.mongodb.MongoNamespace)4 DBObject (com.mongodb.DBObject)3 MongoCommandException (com.mongodb.MongoCommandException)3 BsonString (org.bson.BsonString)3 BsonValue (org.bson.BsonValue)3 Ignore (org.junit.Ignore)3 Test (org.junit.jupiter.api.Test)3 TestCommandListener (com.mongodb.internal.connection.TestCommandListener)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 Before (org.junit.Before)2