Search in sources :

Example 26 with MongoDatabase

use of com.mongodb.client.MongoDatabase in project presto by prestodb.

the class MongoSession method createTableMetadata.

private void createTableMetadata(SchemaTableName schemaTableName, List<MongoColumnHandle> columns) throws TableNotFoundException {
    String schemaName = schemaTableName.getSchemaName();
    String tableName = schemaTableName.getTableName();
    MongoDatabase db = client.getDatabase(schemaName);
    Document metadata = new Document(TABLE_NAME_KEY, tableName);
    ArrayList<Document> fields = new ArrayList<>();
    if (!columns.stream().anyMatch(c -> c.getName().equals("_id"))) {
        fields.add(new MongoColumnHandle("_id", OBJECT_ID, true).getDocument());
    }
    fields.addAll(columns.stream().map(MongoColumnHandle::getDocument).collect(toList()));
    metadata.append(FIELDS_KEY, fields);
    MongoCollection<Document> schema = db.getCollection(schemaCollection);
    schema.createIndex(new Document(TABLE_NAME_KEY, 1), new IndexOptions().unique(true));
    schema.insertOne(metadata);
}
Also used : Document(org.bson.Document) Arrays(java.util.Arrays) LoadingCache(com.google.common.cache.LoadingCache) TypeManager(com.facebook.presto.spi.type.TypeManager) Date(java.util.Date) MongoDatabase(com.mongodb.client.MongoDatabase) BIGINT(com.facebook.presto.spi.type.BigintType.BIGINT) SchemaTableName(com.facebook.presto.spi.SchemaTableName) BOOLEAN(com.facebook.presto.spi.type.BooleanType.BOOLEAN) SchemaNotFoundException(com.facebook.presto.spi.SchemaNotFoundException) Map(java.util.Map) TypeSignatureParameter(com.facebook.presto.spi.type.TypeSignatureParameter) StandardTypes(com.facebook.presto.spi.type.StandardTypes) Collectors.toSet(java.util.stream.Collectors.toSet) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) Collectors(java.util.stream.Collectors) Preconditions.checkState(com.google.common.base.Preconditions.checkState) CacheLoader(com.google.common.cache.CacheLoader) TupleDomain(com.facebook.presto.spi.predicate.TupleDomain) Domain(com.facebook.presto.spi.predicate.Domain) List(java.util.List) FindIterable(com.mongodb.client.FindIterable) Optional(java.util.Optional) CacheBuilder(com.google.common.cache.CacheBuilder) TypeSignature(com.facebook.presto.spi.type.TypeSignature) IntStream(java.util.stream.IntStream) DOUBLE(com.facebook.presto.spi.type.DoubleType.DOUBLE) MongoCollection(com.mongodb.client.MongoCollection) Slice(io.airlift.slice.Slice) Logger(io.airlift.log.Logger) OBJECT_ID(com.facebook.presto.mongodb.ObjectIdType.OBJECT_ID) MINUTES(java.util.concurrent.TimeUnit.MINUTES) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ImmutableList(com.google.common.collect.ImmutableList) MongoCursor(com.mongodb.client.MongoCursor) Verify.verify(com.google.common.base.Verify.verify) Type(com.facebook.presto.spi.type.Type) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) NamedTypeSignature(com.facebook.presto.spi.type.NamedTypeSignature) Objects.requireNonNull(java.util.Objects.requireNonNull) TIMESTAMP(com.facebook.presto.spi.type.TimestampType.TIMESTAMP) Throwables(com.google.common.base.Throwables) Range(com.facebook.presto.spi.predicate.Range) IndexOptions(com.mongodb.client.model.IndexOptions) ExecutionException(java.util.concurrent.ExecutionException) VarcharType.createUnboundedVarcharType(com.facebook.presto.spi.type.VarcharType.createUnboundedVarcharType) Collectors.toList(java.util.stream.Collectors.toList) TableNotFoundException(com.facebook.presto.spi.TableNotFoundException) ColumnHandle(com.facebook.presto.spi.ColumnHandle) MongoClient(com.mongodb.MongoClient) DeleteResult(com.mongodb.client.result.DeleteResult) ObjectId(org.bson.types.ObjectId) HOURS(java.util.concurrent.TimeUnit.HOURS) VisibleForTesting(com.google.common.annotations.VisibleForTesting) IndexOptions(com.mongodb.client.model.IndexOptions) ArrayList(java.util.ArrayList) Document(org.bson.Document) MongoDatabase(com.mongodb.client.MongoDatabase)

Example 27 with MongoDatabase

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

the class DatabaseAcceptanceTest method shouldBeAbleToListAllTheDatabasesAvailable.

@Test
public void shouldBeAbleToListAllTheDatabasesAvailable() {
    MongoClient mongoClient = getMongoClient();
    MongoDatabase firstDatabase = mongoClient.getDatabase("FirstNewDatabase");
    MongoDatabase secondDatabase = mongoClient.getDatabase("SecondNewDatabase");
    MongoDatabase otherDatabase = mongoClient.getDatabase("DatabaseThatDoesNotExistYet");
    try {
        // given
        firstDatabase.getCollection("coll").insertOne(new Document("aDoc", "to force database creation"));
        secondDatabase.getCollection("coll").insertOne(new Document("aDoc", "to force database creation"));
        //when
        List<String> databaseNames = mongoClient.listDatabaseNames().into(new ArrayList<String>());
        //then
        assertThat(databaseNames, hasItems(firstDatabase.getName(), secondDatabase.getName()));
        assertThat(databaseNames, not(hasItem(otherDatabase.getName())));
    } finally {
        //tear down
        firstDatabase.drop();
        secondDatabase.drop();
    }
}
Also used : MongoClient(com.mongodb.MongoClient) Fixture.getMongoClient(com.mongodb.Fixture.getMongoClient) Document(org.bson.Document) MongoDatabase(com.mongodb.client.MongoDatabase) Test(org.junit.Test)

Example 28 with MongoDatabase

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

the class ClientAcceptanceTest method shouldBeAbleToListAllTheDatabaseNamesAvailable.

@Test
public void shouldBeAbleToListAllTheDatabaseNamesAvailable() {
    MongoDatabase firstDatabase = client.getDatabase("FirstNewDatabase");
    MongoDatabase secondDatabase = client.getDatabase("SecondNewDatabase");
    MongoDatabase otherDatabase = client.getDatabase("DatabaseThatDoesNotExistYet");
    try {
        // given
        firstDatabase.getCollection("coll").insertOne(new Document("aDoc", "to force database creation"));
        secondDatabase.getCollection("coll").insertOne(new Document("aDoc", "to force database creation"));
        //when
        List<String> databaseNames = client.listDatabaseNames().into(new ArrayList<String>());
        //then
        assertThat(databaseNames, hasItems(firstDatabase.getName(), secondDatabase.getName()));
        assertThat(databaseNames, not(hasItem(otherDatabase.getName())));
    } finally {
        //tear down
        firstDatabase.drop();
        secondDatabase.drop();
    }
}
Also used : Document(org.bson.Document) MongoDatabase(com.mongodb.client.MongoDatabase) Test(org.junit.Test)

Example 29 with MongoDatabase

use of com.mongodb.client.MongoDatabase in project morphia by mongodb.

the class AggregationTest method testBypassDocumentValidation.

@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());
}
Also used : MongoCommandException(com.mongodb.MongoCommandException) CreateCollectionOptions(com.mongodb.client.model.CreateCollectionOptions) ValidationOptions(com.mongodb.client.model.ValidationOptions) Date(java.util.Date) MongoDatabase(com.mongodb.client.MongoDatabase) Test(org.junit.Test)

Example 30 with MongoDatabase

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

the class Decimal128QuickTour 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");
    // get a handle to the "test" collection
    MongoCollection<Document> collection = database.getCollection("test");
    // drop all the data in it
    collection.drop();
    // make a document and insert it
    Document doc = new Document("name", "MongoDB").append("amount1", Decimal128.parse(".10")).append("amount2", new Decimal128(42L)).append("amount3", new Decimal128(new BigDecimal(".200")));
    collection.insertOne(doc);
    Document first = collection.find().filter(Filters.eq("amount1", new Decimal128(new BigDecimal(".10")))).first();
    Decimal128 amount3 = (Decimal128) first.get("amount3");
    BigDecimal amount2AsBigDecimal = amount3.bigDecimalValue();
    System.out.println(amount3.toString());
    System.out.println(amount2AsBigDecimal.toString());
}
Also used : MongoClient(com.mongodb.MongoClient) MongoClientURI(com.mongodb.MongoClientURI) Decimal128(org.bson.types.Decimal128) Document(org.bson.Document) BigDecimal(java.math.BigDecimal) MongoDatabase(com.mongodb.client.MongoDatabase)

Aggregations

MongoDatabase (com.mongodb.client.MongoDatabase)34 Document (org.bson.Document)25 MongoClient (com.mongodb.MongoClient)14 Test (org.junit.Test)7 ArrayList (java.util.ArrayList)6 MongoClientURI (com.mongodb.MongoClientURI)5 Bson (org.bson.conversions.Bson)4 ServerAddress (com.mongodb.ServerAddress)3 MongoCollection (com.mongodb.client.MongoCollection)3 CreateCollectionOptions (com.mongodb.client.model.CreateCollectionOptions)3 IndexOptions (com.mongodb.client.model.IndexOptions)3 DeleteResult (com.mongodb.client.result.DeleteResult)3 TableNotFoundException (com.facebook.presto.spi.TableNotFoundException)2 NamedTypeSignature (com.facebook.presto.spi.type.NamedTypeSignature)2 TypeSignature (com.facebook.presto.spi.type.TypeSignature)2 ImmutableList (com.google.common.collect.ImmutableList)2 MongoCommandException (com.mongodb.MongoCommandException)2 ValidationOptions (com.mongodb.client.model.ValidationOptions)2 Date (java.util.Date)2 Configuration (com.alibaba.datax.common.util.Configuration)1