Search in sources :

Example 6 with InsertOneOptions

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

the class UnifiedCrudHelper method executeInsertOne.

OperationResult executeInsertOne(final BsonDocument operation) {
    MongoCollection<BsonDocument> collection = entities.getCollection(operation.getString("object").getValue());
    BsonDocument arguments = operation.getDocument("arguments");
    ClientSession session = getSession(arguments);
    BsonDocument document = arguments.getDocument("document").asDocument();
    InsertOneOptions options = new InsertOneOptions();
    for (Map.Entry<String, BsonValue> cur : arguments.entrySet()) {
        switch(cur.getKey()) {
            case "session":
            case "document":
                break;
            default:
                throw new UnsupportedOperationException("Unsupported argument: " + cur.getKey());
        }
    }
    return resultOf(() -> toExpected(session == null ? collection.insertOne(document, options) : collection.insertOne(session, document, options)));
}
Also used : BsonDocument(org.bson.BsonDocument) InsertOneOptions(com.mongodb.client.model.InsertOneOptions) ClientSession(com.mongodb.client.ClientSession) BsonString(org.bson.BsonString) Map(java.util.Map) BsonValue(org.bson.BsonValue)

Example 7 with InsertOneOptions

use of com.mongodb.client.model.InsertOneOptions in project debezium by debezium.

the class ConnectionIT method shouldCreateMovieDatabase.

@Test
public void shouldCreateMovieDatabase() {
    Testing.print("Configuration: " + config);
    String dbName = "dbA";
    primary.execute("shouldCreateMovieDatabase", mongo -> {
        Testing.debug("Getting or creating 'movies' collection");
        // Create a database and a collection in that database ...
        MongoDatabase db = mongo.getDatabase(dbName);
        // Get or create a collection in that database ...
        db.getCollection("movies");
        Testing.debug("Completed getting 'movies' collection");
    });
    primary.execute("Add document to movies collection", mongo -> {
        Testing.debug("Adding document to 'movies' collection");
        // Add a document to that collection ...
        MongoDatabase db = mongo.getDatabase(dbName);
        MongoCollection<Document> movies = db.getCollection("movies");
        InsertOneOptions insertOptions = new InsertOneOptions().bypassDocumentValidation(true);
        movies.insertOne(Document.parse("{ \"name\":\"Starter Wars\"}"), insertOptions);
        assertThat(db.getCollection("movies").count()).isEqualTo(1);
        // Read the collection to make sure we can find our document ...
        Bson filter = Filters.eq("name", "Starter Wars");
        FindIterable<Document> movieResults = db.getCollection("movies").find(filter);
        try (MongoCursor<Document> cursor = movieResults.iterator()) {
            assertThat(cursor.tryNext().getString("name")).isEqualTo("Starter Wars");
            assertThat(cursor.tryNext()).isNull();
        }
        Testing.debug("Completed document to 'movies' collection");
    });
    // Now that we've put at least one document into our collection, verify we can see the database and collection ...
    assertThat(primary.databaseNames()).contains("dbA");
    assertThat(primary.collections()).contains(new CollectionId(replicaSet.replicaSetName(), dbName, "movies"));
    // Read oplog from beginning ...
    List<Document> eventQueue = new LinkedList<>();
    int minimumEventsExpected = 1;
    long maxSeconds = 5;
    primary.execute("read oplog from beginning", mongo -> {
        Testing.debug("Getting local.oplog.rs");
        BsonTimestamp oplogStart = new BsonTimestamp(1, 1);
        Bson filter = // start just after our last position
        Filters.and(// start just after our last position
        Filters.gt("ts", oplogStart), // skip internal movements across shards
        Filters.exists("fromMigrate", false));
        FindIterable<Document> results = mongo.getDatabase("local").getCollection("oplog.rs").find(filter).sort(new Document("$natural", 1)).oplogReplay(// tells Mongo to not rely on indexes
        true).noCursorTimeout(// don't timeout waiting for events
        true).cursorType(CursorType.TailableAwait);
        Testing.debug("Reading local.oplog.rs");
        try (MongoCursor<Document> cursor = results.iterator()) {
            Document event = null;
            long stopTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(maxSeconds);
            while (System.currentTimeMillis() < stopTime && eventQueue.size() < minimumEventsExpected) {
                while ((event = cursor.tryNext()) != null) {
                    eventQueue.add(event);
                }
            }
            assertThat(eventQueue.size()).isGreaterThanOrEqualTo(1);
        }
        Testing.debug("Completed local.oplog.rs");
    });
    eventQueue.forEach(event -> {
        Testing.print("Found: " + event);
        BsonTimestamp position = event.get("ts", BsonTimestamp.class);
        assert position != null;
    });
}
Also used : InsertOneOptions(com.mongodb.client.model.InsertOneOptions) Document(org.bson.Document) LinkedList(java.util.LinkedList) BsonTimestamp(org.bson.BsonTimestamp) Bson(org.bson.conversions.Bson) MongoDatabase(com.mongodb.client.MongoDatabase) Test(org.junit.Test)

Aggregations

InsertOneOptions (com.mongodb.client.model.InsertOneOptions)7 Document (org.bson.Document)4 MongoDatabase (com.mongodb.client.MongoDatabase)3 BsonDocument (org.bson.BsonDocument)3 Test (org.junit.Test)3 InsertOneResult (com.mongodb.client.result.InsertOneResult)2 LinkedList (java.util.LinkedList)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 Struct (org.apache.kafka.connect.data.Struct)2 SourceRecord (org.apache.kafka.connect.source.SourceRecord)2 Bson (org.bson.conversions.Bson)2 ClientSession (com.mongodb.client.ClientSession)1 FindIterable (com.mongodb.client.FindIterable)1 MongoCollection (com.mongodb.client.MongoCollection)1 MongoCursor (com.mongodb.client.MongoCursor)1 Filters (com.mongodb.client.model.Filters)1 JSON (com.mongodb.util.JSON)1 Operation (io.debezium.data.Envelope.Operation)1 VerifyRecord (io.debezium.data.VerifyRecord)1 AbstractConnectorTest (io.debezium.embedded.AbstractConnectorTest)1