Java Code Examples for com.mongodb.client.MongoClients#create()
The following examples show how to use
com.mongodb.client.MongoClients#create() .
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: MongoDBIOIT.java From beam with Apache License 2.0 | 7 votes |
@BeforeClass public static void setUp() { PipelineOptionsFactory.register(MongoDBPipelineOptions.class); options = TestPipeline.testingPipelineOptions().as(MongoDBPipelineOptions.class); collection = String.format("test_%s", new Date().getTime()); bigQueryDataset = options.getBigQueryDataset(); bigQueryTable = options.getBigQueryTable(); mongoUrl = String.format("mongodb://%s:%s", options.getMongoDBHostName(), options.getMongoDBPort()); mongoClient = MongoClients.create(mongoUrl); settings = InfluxDBSettings.builder() .withHost(options.getInfluxHost()) .withDatabase(options.getInfluxDatabase()) .withMeasurement(options.getInfluxMeasurement()) .get(); }
Example 2
Source File: ProjectionsBenchmark.java From spring-data-dev-tools with Apache License 2.0 | 6 votes |
@Setup public void setUp() { client = MongoClients.create(); template = new MongoTemplate(client, DB_NAME); source = new Person(); source.firstname = "luke"; source.lastname = "skywalker"; source.address = new Address(); source.address.street = "melenium falcon 1"; source.address.city = "deathstar"; template.save(source, COLLECTION_NAME); asPerson = template.query(Person.class).inCollection(COLLECTION_NAME); asDtoProjection = template.query(Person.class).inCollection(COLLECTION_NAME).as(DtoProjection.class); asClosedProjection = template.query(Person.class).inCollection(COLLECTION_NAME).as(ClosedProjection.class); asOpenProjection = template.query(Person.class).inCollection(COLLECTION_NAME).as(OpenProjection.class); asPersonWithFieldsRestriction = template.query(Person.class).inCollection(COLLECTION_NAME) .matching(new BasicQuery(new Document(), fields)); mongoCollection = client.getDatabase(DB_NAME).getCollection(COLLECTION_NAME); }
Example 3
Source File: TestBase.java From morphia with Apache License 2.0 | 6 votes |
protected TestBase() { Builder builder = MongoClientSettings.builder(); try { builder.uuidRepresentation(mapperOptions.getUuidRepresentation()); } catch(Exception ignored) { // not a 4.0 driver } MongoClientSettings clientSettings = builder .applyConnectionString(new ConnectionString(getMongoURI())) .build(); this.mongoClient = MongoClients.create(clientSettings); this.database = getMongoClient().getDatabase(TEST_DB_NAME); this.ds = Morphia.createDatastore(getMongoClient(), database.getName()); ds.setQueryFactory(new DefaultQueryFactory()); }
Example 4
Source File: MongoDb4Provider.java From logging-log4j2 with Apache License 2.0 | 6 votes |
private MongoDb4Provider(final String connectionStringSource, final boolean isCapped, final Integer collectionSize) { LOGGER.debug("Creating ConnectionString {}...", connectionStringSource); this.connectionString = new ConnectionString(connectionStringSource); LOGGER.debug("Created ConnectionString {}", connectionString); LOGGER.debug("Creating MongoClientSettings..."); // @formatter:off final MongoClientSettings settings = MongoClientSettings.builder() .applyConnectionString(this.connectionString) .codecRegistry(CODEC_REGISTRIES) .build(); // @formatter:on LOGGER.debug("Created MongoClientSettings {}", settings); LOGGER.debug("Creating MongoClient {}...", settings); this.mongoClient = MongoClients.create(settings); LOGGER.debug("Created MongoClient {}", mongoClient); String databaseName = this.connectionString.getDatabase(); LOGGER.debug("Getting MongoDatabase {}...", databaseName); this.mongoDatabase = this.mongoClient.getDatabase(databaseName); LOGGER.debug("Got MongoDatabase {}", mongoDatabase); this.isCapped = isCapped; this.collectionSize = collectionSize; }
Example 5
Source File: Datastore.java From mangooio with Apache License 2.0 | 5 votes |
private void connect() { this.mongoClient = MongoClients.create(getConnectionString()); this.datastore = Morphia.createDatastore(this.mongoClient, this.config.getMongoDbName()); this.datastore.getMapper().mapPackage(this.config.getMongoPackage()); LOG.info("Created MongoClient connected to {}:{} with credentials = {}", this.config.getMongoHost(), this.config.getMongoPort(), this.config.isMongoAuth()); LOG.info("Mapped Morphia models of package '{}' and created Morphia Datastore conntected to database '{}'", this.config.getMongoPackage(), this.config.getMongoDbName()); }
Example 6
Source File: MongoLockProviderIntegrationTest.java From ShedLock with Apache License 2.0 | 5 votes |
@BeforeAll public static void startMongo() throws IOException { mongodExe = starter.prepare(new MongodConfigBuilder() .version(Version.Main.V3_6) .build()); mongod = mongodExe.start(); mongo = MongoClients.create("mongodb://localhost:"+mongod.getConfig().net().getPort()); }
Example 7
Source File: MongoDBSourceTest.java From hazelcast-jet-contrib with Apache License 2.0 | 5 votes |
static MongoClient mongoClient(String connectionString, int connectionTimeoutSeconds) { MongoClientSettings settings = MongoClientSettings .builder() .applyConnectionString(new ConnectionString(connectionString)) .applyToClusterSettings(b -> { b.serverSelectionTimeout(connectionTimeoutSeconds, SECONDS); }) .build(); return MongoClients.create(settings); }
Example 8
Source File: MongoClientCustomizer.java From syndesis with Apache License 2.0 | 5 votes |
@Override public void customize(ComponentProxyComponent component, Map<String, Object> options) { MongoCustomizersUtil.replaceAdminDBIfMissing(options); // Set connection parameter if (!options.containsKey("mongoConnection")) { if (options.containsKey("user") && options.containsKey("password") && options.containsKey("host")) { ConnectionParamsConfiguration mongoConf = new ConnectionParamsConfiguration(cast(options)); // We need to force consumption in order to perform property placeholder done by Camel consumeOption(camelContext, options, "password", String.class, mongoConf::setPassword); LOGGER.debug("Creating and registering a client connection to {}", mongoConf); MongoClientSettings.Builder settings = MongoClientSettings.builder(); MongoCredential credentials = MongoCredential.createCredential( mongoConf.getUser(), mongoConf.getAdminDB(), mongoConf.getPassword().toCharArray()); ConnectionString uri = new ConnectionString(mongoConf.getMongoClientURI()); settings.applyConnectionString(uri); settings.credential(credentials); MongoClient mongoClient = MongoClients.create(settings.build()); options.put("mongoConnection", mongoClient); if (!options.containsKey("connectionBean")) { //We safely put a default name instead of leaving null options.put("connectionBean", String.format("%s-%s", mongoConf.getHost(), mongoConf.getUser())); } } else { LOGGER.warn( "Not enough information provided to set-up the MongoDB client. Required at least host, user and " + "password."); } } }
Example 9
Source File: MongoWithReplicasTestBase.java From quarkus with Apache License 2.0 | 5 votes |
private static void initializeReplicaSet(final List<IMongodConfig> mongodConfigList) throws UnknownHostException { final String arbitrerAddress = "mongodb://" + mongodConfigList.get(0).net().getServerAddress().getHostName() + ":" + mongodConfigList.get(0).net().getPort(); final MongoClientSettings mo = MongoClientSettings.builder() .applyConnectionString(new ConnectionString(arbitrerAddress)).build(); try (MongoClient mongo = MongoClients.create(mo)) { final MongoDatabase mongoAdminDB = mongo.getDatabase("admin"); Document cr = mongoAdminDB.runCommand(new Document("isMaster", 1)); LOGGER.infof("isMaster: %s", cr); // Build replica set configuration settings final Document rsConfiguration = buildReplicaSetConfiguration(mongodConfigList); LOGGER.infof("replSetSettings: %s", rsConfiguration); // Initialize replica set cr = mongoAdminDB.runCommand(new Document("replSetInitiate", rsConfiguration)); LOGGER.infof("replSetInitiate: %s", cr); // Check replica set status before to proceed await() .pollInterval(100, TimeUnit.MILLISECONDS) .atMost(1, TimeUnit.MINUTES) .until(() -> { Document result = mongoAdminDB.runCommand(new Document("replSetGetStatus", 1)); LOGGER.infof("replSetGetStatus: %s", result); return !isReplicaSetStarted(result); }); } }
Example 10
Source File: ConnectorValidationTest.java From mongo-kafka with Apache License 2.0 | 5 votes |
private boolean isReplicaSetOrSharded() { try (MongoClient mongoClient = MongoClients.create(getConnectionString())) { Document isMaster = mongoClient.getDatabase("admin").runCommand(BsonDocument.parse("{isMaster: 1}")); return isMaster.containsKey("setName") || isMaster.get("msg", "").equals("isdbgrid"); } catch (Exception e) { return false; } }
Example 11
Source File: MongodbDriver.java From hazelcast-simulator with Apache License 2.0 | 5 votes |
@Override public void startVendorInstance() throws Exception { String address = get("node"); String[] addressParts = address.split(":"); if (addressParts.length == 0 || addressParts.length > 2) { throw new IllegalArgumentException("Invalid node address. Example: localhost:11211"); } StringBuilder sb = new StringBuilder("mongodb://").append(address); if (addressParts.length == 1) { sb.append(":27017"); //default MongoDB port } this.client = MongoClients.create(sb.toString()); }
Example 12
Source File: JaversSpringMongoApplicationConfig.java From javers with Apache License 2.0 | 4 votes |
/** * MongoDB setup */ @Bean(name="realMongoClient") @ConditionalOnMissingBean public MongoClient mongo() { return MongoClients.create(); }
Example 13
Source File: MongoDBLocalContainerService.java From camel-kafka-connector with Apache License 2.0 | 4 votes |
@Override public MongoClient getClient() { return MongoClients.create(getReplicaSetUrl()); }
Example 14
Source File: MongoConfig.java From biliob_backend with MIT License | 4 votes |
/** * Use the Reactive Streams Mongo Client API to create a * com.mongodb.reactivestreams.client.MongoClient instance. */ public @Bean MongoClient reactiveMongoClient() { return MongoClients.create(MongoConfig.BILIOB_MONGO_URL); }
Example 15
Source File: MongoDBHelper.java From mongo-kafka with Apache License 2.0 | 4 votes |
public MongoClient getMongoClient() { if (mongoClient == null) { mongoClient = MongoClients.create(getConnectionString()); } return mongoClient; }
Example 16
Source File: ConnectorValidationTest.java From mongo-kafka with Apache License 2.0 | 4 votes |
private MongoClient getMongoClient() { if (mongoClient == null) { mongoClient = MongoClients.create(getConnectionString()); } return mongoClient; }
Example 17
Source File: EmbeddedMongo.java From spring-data-examples with Apache License 2.0 | 4 votes |
default MongoClient mongoClient() { return MongoClients.create(connectionString()); }
Example 18
Source File: MappingMongoConverterBenchmark.java From spring-data-dev-tools with Apache License 2.0 | 4 votes |
@Setup public void setUp() throws Exception { client = MongoClients.create(); this.mappingContext = new MongoMappingContext(); this.mappingContext.setInitialEntitySet(Collections.singleton(Customer.class)); this.mappingContext.afterPropertiesSet(); DbRefResolver dbRefResolver = new DefaultDbRefResolver(new SimpleMongoClientDatabaseFactory(client, DB_NAME)); this.converter = new MappingMongoConverter(dbRefResolver, mappingContext); this.converter.setCustomConversions(new MongoCustomConversions(Collections.emptyList())); this.converter.afterPropertiesSet(); // just a flat document this.documentWith2Properties = new Document("firstname", "Dave").append("lastname", "Matthews"); // document with a nested one Document address = new Document("zipCode", "ABCDE").append("city", "Some Place"); this.documentWith2PropertiesAnd1Nested = new Document("firstname", "Dave").// append("lastname", "Matthews").// append("address", address); // object equivalent of documentWith2PropertiesAnd1Nested this.objectWith2PropertiesAnd1Nested = new Customer("Dave", "Matthews", new Address("zipCode", "City")); // a bit more challenging object with list & map conversion. objectWithFlatAndComplexPropertiesPlusListAndMap = new SlightlyMoreComplexObject(); objectWithFlatAndComplexPropertiesPlusListAndMap.id = UUID.randomUUID().toString(); objectWithFlatAndComplexPropertiesPlusListAndMap.addressList = Arrays.asList(new Address("zip-1", "city-1"), new Address("zip-2", "city-2")); objectWithFlatAndComplexPropertiesPlusListAndMap.customer = objectWith2PropertiesAnd1Nested; objectWithFlatAndComplexPropertiesPlusListAndMap.customerMap = new LinkedHashMap<>(); objectWithFlatAndComplexPropertiesPlusListAndMap.customerMap.put("dave", objectWith2PropertiesAnd1Nested); objectWithFlatAndComplexPropertiesPlusListAndMap.customerMap.put("deborah", new Customer("Deborah Anne", "Dyer", new Address("?", "london"))); objectWithFlatAndComplexPropertiesPlusListAndMap.customerMap.put("eddie", new Customer("Eddie", "Vedder", new Address("??", "Seattle"))); objectWithFlatAndComplexPropertiesPlusListAndMap.intOne = Integer.MIN_VALUE; objectWithFlatAndComplexPropertiesPlusListAndMap.intTwo = Integer.MAX_VALUE; objectWithFlatAndComplexPropertiesPlusListAndMap.location = new Point(-33.865143, 151.209900); objectWithFlatAndComplexPropertiesPlusListAndMap.renamedField = "supercalifragilisticexpialidocious"; objectWithFlatAndComplexPropertiesPlusListAndMap.stringOne = "¯\\_(ツ)_/¯"; objectWithFlatAndComplexPropertiesPlusListAndMap.stringTwo = " (╯°□°)╯︵ ┻━┻"; // JSON equivalent of objectWithFlatAndComplexPropertiesPlusListAndMap documentWithFlatAndComplexPropertiesPlusListAndMap = Document.parse( "{ \"_id\" : \"517f6aee-e9e0-44f0-88ed-f3694a019f27\", \"intOne\" : -2147483648, \"intTwo\" : 2147483647, \"stringOne\" : \"¯\\\\_(ツ)_/¯\", \"stringTwo\" : \" (╯°□°)╯︵ ┻━┻\", \"explicit-field-name\" : \"supercalifragilisticexpialidocious\", \"location\" : { \"x\" : -33.865143, \"y\" : 151.2099 }, \"objectWith2PropertiesAnd1Nested\" : { \"firstname\" : \"Dave\", \"lastname\" : \"Matthews\", \"address\" : { \"zipCode\" : \"zipCode\", \"city\" : \"City\" } }, \"addressList\" : [{ \"zipCode\" : \"zip-1\", \"city\" : \"city-1\" }, { \"zipCode\" : \"zip-2\", \"city\" : \"city-2\" }], \"customerMap\" : { \"dave\" : { \"firstname\" : \"Dave\", \"lastname\" : \"Matthews\", \"address\" : { \"zipCode\" : \"zipCode\", \"city\" : \"City\" } }, \"deborah\" : { \"firstname\" : \"Deborah Anne\", \"lastname\" : \"Dyer\", \"address\" : { \"zipCode\" : \"?\", \"city\" : \"london\" } }, \"eddie\" : { \"firstname\" : \"Eddie\", \"lastname\" : \"Vedder\", \"address\" : { \"zipCode\" : \"??\", \"city\" : \"Seattle\" } } }, \"_class\" : \"org.springframework.data.mongodb.core.convert.MappingMongoConverterBenchmark$SlightlyMoreComplexObject\" }"); }
Example 19
Source File: MongoDBContainerTest.java From testcontainers-java with MIT License | 4 votes |
/** * Taken from <a href="https://docs.mongodb.com/manual/core/transactions/">https://docs.mongodb.com</a> */ @Test public void shouldExecuteTransactions() { try ( // creatingMongoDBContainer { final MongoDBContainer mongoDBContainer = new MongoDBContainer() // } ) { // startingMongoDBContainer { mongoDBContainer.start(); // } final String mongoRsUrl = mongoDBContainer.getReplicaSetUrl(); assertNotNull(mongoRsUrl); final MongoClient mongoSyncClient = MongoClients.create(mongoRsUrl); mongoSyncClient.getDatabase("mydb1").getCollection("foo") .withWriteConcern(WriteConcern.MAJORITY).insertOne(new Document("abc", 0)); mongoSyncClient.getDatabase("mydb2").getCollection("bar") .withWriteConcern(WriteConcern.MAJORITY).insertOne(new Document("xyz", 0)); final ClientSession clientSession = mongoSyncClient.startSession(); final TransactionOptions txnOptions = TransactionOptions.builder() .readPreference(ReadPreference.primary()) .readConcern(ReadConcern.LOCAL) .writeConcern(WriteConcern.MAJORITY) .build(); final String trxResult = "Inserted into collections in different databases"; TransactionBody<String> txnBody = () -> { final MongoCollection<Document> coll1 = mongoSyncClient.getDatabase("mydb1").getCollection("foo"); final MongoCollection<Document> coll2 = mongoSyncClient.getDatabase("mydb2").getCollection("bar"); coll1.insertOne(clientSession, new Document("abc", 1)); coll2.insertOne(clientSession, new Document("xyz", 999)); return trxResult; }; try { final String trxResultActual = clientSession.withTransaction(txnBody, txnOptions); assertEquals(trxResult, trxResultActual); } catch (RuntimeException re) { throw new IllegalStateException(re.getMessage(), re); } finally { clientSession.close(); mongoSyncClient.close(); } } }
Example 20
Source File: RemoteMongoDBService.java From camel-kafka-connector with Apache License 2.0 | 4 votes |
@Override public MongoClient getClient() { return MongoClients.create(getReplicaSetUrl()); }