Search in sources :

Example 21 with MongoClient

use of com.mongodb.client.MongoClient in project aion by aionnetwork.

the class MongoConnectionManager method getMongoClientInstance.

public synchronized MongoClient getMongoClientInstance(String mongoClientUri) {
    MongoClient mongoClient;
    if (!this.mongoUriToClientMap.containsKey(mongoClientUri)) {
        System.out.println("Creating new mongo client to connect to " + mongoClientUri);
        mongoClient = MongoClients.create(mongoClientUri);
        this.mongoUriToClientMap.put(mongoClientUri, mongoClient);
        this.activeClientCountMap.put(mongoClientUri, new AtomicInteger(1));
    } else {
        System.out.println("Reusing existing mongo client for " + mongoClientUri);
        mongoClient = this.mongoUriToClientMap.get(mongoClientUri);
        this.activeClientCountMap.get(mongoClientUri).incrementAndGet();
    }
    return mongoClient;
}
Also used : MongoClient(com.mongodb.client.MongoClient) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 22 with MongoClient

use of com.mongodb.client.MongoClient in project aion by aionnetwork.

the class MongoDB method open.

@Override
public boolean open() {
    if (isOpen()) {
        return true;
    }
    LOG.info("Initializing MongoDB at {}", mongoClientUri);
    // Get the client and create a session for this instance
    MongoClient mongoClient = MongoConnectionManager.inst().getMongoClientInstance(this.mongoClientUri);
    ClientSessionOptions sessionOptions = ClientSessionOptions.builder().causallyConsistent(true).defaultTransactionOptions(TransactionOptions.builder().readConcern(ReadConcern.DEFAULT).writeConcern(WriteConcern.MAJORITY).readPreference(ReadPreference.nearest()).build()).build();
    this.clientSession = mongoClient.startSession(sessionOptions);
    // Get the database and our collection. Mongo takes care of creating these if they don't
    // exist
    MongoDatabase mongoDb = mongoClient.getDatabase(MongoConstants.AION_DB_NAME);
    // Gets the collection where we will be saving our values. Mongo creates it if it doesn't
    // yet exist
    this.collection = mongoDb.getCollection(this.name, BsonDocument.class);
    LOG.info("Finished opening the Mongo connection");
    return isOpen();
}
Also used : MongoClient(com.mongodb.client.MongoClient) BsonDocument(org.bson.BsonDocument) ClientSessionOptions(com.mongodb.ClientSessionOptions) MongoDatabase(com.mongodb.client.MongoDatabase)

Example 23 with MongoClient

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

the class CausalConsistencyExamples method setupDatabase.

private static void setupDatabase() {
    MongoClient client = MongoClients.create();
    client.getDatabase("test").drop();
    MongoDatabase database = client.getDatabase("test");
    database.getCollection("items").drop();
    MongoCollection<Document> items = database.getCollection("items");
    Document document = new Document("sku", "111").append("name", "Peanuts").append("start", new Date());
    items.insertOne(document);
    client.close();
}
Also used : MongoClient(com.mongodb.client.MongoClient) Document(org.bson.Document) Date(java.util.Date) MongoDatabase(com.mongodb.client.MongoDatabase)

Example 24 with MongoClient

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

the class CausalConsistencyExamples 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) {
    setupDatabase();
    MongoClient client = MongoClients.create();
    // Start Causal Consistency Example 1
    // Example 1: Use a causally consistent session to ensure that the update occurs before the insert.
    ClientSession session1 = client.startSession(ClientSessionOptions.builder().causallyConsistent(true).build());
    Date currentDate = new Date();
    MongoCollection<Document> items = client.getDatabase("test").withReadConcern(ReadConcern.MAJORITY).withWriteConcern(WriteConcern.MAJORITY.withWTimeout(1000, TimeUnit.MILLISECONDS)).getCollection("test");
    items.updateOne(session1, eq("sku", "111"), set("end", currentDate));
    Document document = new Document("sku", "nuts-111").append("name", "Pecans").append("start", currentDate);
    items.insertOne(session1, document);
    // End Causal Consistency Example 1
    // Start Causal Consistency Example 2
    // Example 2: Advance the cluster time and the operation time to that of the other session to ensure that
    // this client is causally consistent with the other session and read after the two writes.
    ClientSession session2 = client.startSession(ClientSessionOptions.builder().causallyConsistent(true).build());
    session2.advanceClusterTime(session1.getClusterTime());
    session2.advanceOperationTime(session1.getOperationTime());
    items = client.getDatabase("test").withReadPreference(ReadPreference.secondary()).withReadConcern(ReadConcern.MAJORITY).withWriteConcern(WriteConcern.MAJORITY.withWTimeout(1000, TimeUnit.MILLISECONDS)).getCollection("items");
    for (Document item : items.find(session2, eq("end", BsonNull.VALUE))) {
        System.out.println(item);
    }
// End Causal Consistency Example 2
}
Also used : MongoClient(com.mongodb.client.MongoClient) ClientSession(com.mongodb.client.ClientSession) Document(org.bson.Document) Date(java.util.Date)

Example 25 with MongoClient

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

the class ChangeStreamSamples 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 = MongoClients.create("mongodb://localhost:27017,localhost:27018,localhost:27019");
    } else {
        mongoClient = MongoClients.create(args[0]);
    }
    // Select the MongoDB database.
    MongoDatabase database = mongoClient.getDatabase("testChangeStreams");
    database.drop();
    sleep();
    // Select the collection to query.
    MongoCollection<Document> collection = database.getCollection("documents");
    /*
         * Example 1
         * Create a simple change stream against an existing collection.
         */
    System.out.println("1. Initial document from the Change Stream:");
    // Create the change stream cursor.
    MongoChangeStreamCursor<ChangeStreamDocument<Document>> cursor = collection.watch().cursor();
    // Insert a test document into the collection.
    collection.insertOne(Document.parse("{username: 'alice123', name: 'Alice'}"));
    ChangeStreamDocument<Document> next = cursor.next();
    System.out.println(next);
    cursor.close();
    sleep();
    /*
         * Example 2
         * Create a change stream with 'lookup' option enabled.
         * The test document will be returned with a full version of the updated document.
         */
    System.out.println("2. Document from the Change Stream, with lookup enabled:");
    // Create the change stream cursor.
    cursor = collection.watch().fullDocument(FullDocument.UPDATE_LOOKUP).cursor();
    // Update the test document.
    collection.updateOne(Document.parse("{username: 'alice123'}"), Document.parse("{$set : { email: 'alice@example.com'}}"));
    // Block until the next result is returned
    next = cursor.next();
    System.out.println(next);
    cursor.close();
    sleep();
    /*
         * Example 3
         * Create a change stream with 'lookup' option using a $match and ($redact or $project) stage.
         */
    System.out.println("3. Document from the Change Stream, with lookup enabled, matching `update` operations only: ");
    // Insert some dummy data.
    collection.insertMany(asList(Document.parse("{updateMe: 1}"), Document.parse("{replaceMe: 1}")));
    // Create $match pipeline stage.
    List<Bson> pipeline = singletonList(Aggregates.match(Filters.or(Document.parse("{'fullDocument.username': 'alice123'}"), Filters.in("operationType", asList("update", "replace", "delete")))));
    // Create the change stream cursor with $match.
    cursor = collection.watch(pipeline).fullDocument(FullDocument.UPDATE_LOOKUP).cursor();
    // Forward to the end of the change stream
    next = cursor.tryNext();
    // Update the test document.
    collection.updateOne(Filters.eq("updateMe", 1), Updates.set("updated", true));
    next = cursor.next();
    System.out.println(format("Update operationType: %s %n %s", next.getUpdateDescription(), next));
    // Replace the test document.
    collection.replaceOne(Filters.eq("replaceMe", 1), Document.parse("{replaced: true}"));
    next = cursor.next();
    System.out.println(format("Replace operationType: %s", next));
    // Delete the test document.
    collection.deleteOne(Filters.eq("username", "alice123"));
    next = cursor.next();
    System.out.println(format("Delete operationType: %s", next));
    cursor.close();
    sleep();
    /**
     * Example 4
     * Resume a change stream using a resume token.
     */
    System.out.println("4. Document from the Change Stream including a resume token:");
    // Get the resume token from the last document we saw in the previous change stream cursor.
    BsonDocument resumeToken = cursor.getResumeToken();
    System.out.println(resumeToken);
    // Pass the resume token to the resume after function to continue the change stream cursor.
    cursor = collection.watch().resumeAfter(resumeToken).cursor();
    // Insert a test document.
    collection.insertOne(Document.parse("{test: 'd'}"));
    // Block until the next result is returned
    next = cursor.next();
    System.out.println(next);
    cursor.close();
}
Also used : MongoClient(com.mongodb.client.MongoClient) BsonDocument(org.bson.BsonDocument) ChangeStreamDocument(com.mongodb.client.model.changestream.ChangeStreamDocument) Document(org.bson.Document) ChangeStreamDocument(com.mongodb.client.model.changestream.ChangeStreamDocument) BsonDocument(org.bson.BsonDocument) FullDocument(com.mongodb.client.model.changestream.FullDocument) MongoDatabase(com.mongodb.client.MongoDatabase) Bson(org.bson.conversions.Bson)

Aggregations

MongoClient (com.mongodb.client.MongoClient)45 Document (org.bson.Document)22 MongoDatabase (com.mongodb.client.MongoDatabase)19 Test (org.junit.Test)10 Map (java.util.Map)9 MongoClientSettings (com.mongodb.MongoClientSettings)8 ServerAddress (com.mongodb.ServerAddress)8 HashMap (java.util.HashMap)7 ConnectionString (com.mongodb.ConnectionString)6 BsonDocument (org.bson.BsonDocument)6 BsonString (org.bson.BsonString)6 Test (org.junit.jupiter.api.Test)6 List (java.util.List)5 SecureRandom (java.security.SecureRandom)4 Set (java.util.Set)4 TimeUnit (java.util.concurrent.TimeUnit)4 BsonValue (org.bson.BsonValue)4 ClientEncryptionSettings (com.mongodb.ClientEncryptionSettings)3 ClientSessionOptions (com.mongodb.ClientSessionOptions)3 ClusterFixture.getMultiMongosConnectionString (com.mongodb.ClusterFixture.getMultiMongosConnectionString)3