Search in sources :

Example 1 with InsertOneResult

use of com.mongodb.client.result.InsertOneResult in project logging-log4j2 by apache.

the class MongoDb4Connection method insertObject.

@Override
public void insertObject(final NoSqlObject<Document> object) {
    try {
        final Document unwrapped = object.unwrap();
        LOGGER.debug("Inserting BSON Document {}", unwrapped);
        InsertOneResult insertOneResult = this.collection.insertOne(unwrapped);
        LOGGER.debug("Insert MongoDb result {}", insertOneResult);
    } catch (final MongoException e) {
        throw new AppenderLoggingException("Failed to write log event to MongoDB due to error: " + e.getMessage(), e);
    }
}
Also used : MongoException(com.mongodb.MongoException) AppenderLoggingException(org.apache.logging.log4j.core.appender.AppenderLoggingException) Document(org.bson.Document) InsertOneResult(com.mongodb.client.result.InsertOneResult)

Example 2 with InsertOneResult

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

the class JsonPoweredCrudTestHelper method getInsertOneResult.

BsonDocument getInsertOneResult(final BsonDocument collectionOptions, final BsonDocument arguments, @Nullable final ClientSession clientSession) {
    BsonDocument document = arguments.getDocument("document");
    InsertOneOptions options = new InsertOneOptions();
    if (arguments.containsKey("bypassDocumentValidation")) {
        options.bypassDocumentValidation(arguments.getBoolean("bypassDocumentValidation").getValue());
    }
    InsertOneResult result;
    if (clientSession == null) {
        result = getCollection(collectionOptions).insertOne(document, options);
    } else {
        result = getCollection(collectionOptions).insertOne(clientSession, document, options);
    }
    return toResult(new BsonDocument("insertedId", result.getInsertedId()));
}
Also used : BsonDocument(org.bson.BsonDocument) InsertOneOptions(com.mongodb.client.model.InsertOneOptions) InsertOneResult(com.mongodb.client.result.InsertOneResult)

Example 3 with InsertOneResult

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

the class ClientSideEncryptionBypassAutoEncryptionTest method shouldAutoDecryptManuallyEncryptedData.

@Test
public void shouldAutoDecryptManuallyEncryptedData() {
    String fieldValue = "123456789";
    ObservableSubscriber<BsonBinary> binarySubscriber = new OperationSubscriber<>();
    clientEncryption.createDataKey("local", new DataKeyOptions()).subscribe(binarySubscriber);
    BsonBinary dataKeyId = binarySubscriber.get().get(0);
    binarySubscriber = new OperationSubscriber<>();
    clientEncryption.encrypt(new BsonString(fieldValue), new EncryptOptions("AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic").keyId(dataKeyId)).subscribe(binarySubscriber);
    BsonBinary encryptedFieldValue = binarySubscriber.get().get(0);
    MongoCollection<Document> collection = clientEncrypted.getDatabase(Fixture.getDefaultDatabaseName()).getCollection("test");
    ObservableSubscriber<InsertOneResult> insertSubscriber = new OperationSubscriber<>();
    collection.insertOne(new Document("encryptedField", encryptedFieldValue)).subscribe(insertSubscriber);
    insertSubscriber.await();
    ObservableSubscriber<Document> resultSubscriber = new OperationSubscriber<>();
    collection.find().first().subscribe(resultSubscriber);
    assertEquals(fieldValue, resultSubscriber.get().get(0).getString("encryptedField"));
}
Also used : BsonBinary(org.bson.BsonBinary) OperationSubscriber(reactivestreams.helpers.SubscriberHelpers.OperationSubscriber) BsonString(org.bson.BsonString) Document(org.bson.Document) DataKeyOptions(com.mongodb.client.model.vault.DataKeyOptions) EncryptOptions(com.mongodb.client.model.vault.EncryptOptions) BsonString(org.bson.BsonString) InsertOneResult(com.mongodb.client.result.InsertOneResult) Test(org.junit.Test)

Example 4 with InsertOneResult

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

the class PojoQuickTour 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();
    } else {
        mongoClient = MongoClients.create(args[0]);
    }
    // create codec registry for POJOs
    CodecRegistry pojoCodecRegistry = fromRegistries(MongoClients.getDefaultCodecRegistry(), fromProviders(PojoCodecProvider.builder().automatic(true).build()));
    // get handle to "mydb" database
    MongoDatabase database = mongoClient.getDatabase("mydb").withCodecRegistry(pojoCodecRegistry);
    // get a handle to the "people" collection
    final MongoCollection<Person> collection = database.getCollection("people", Person.class);
    // drop all the data in it
    ObservableSubscriber<Void> successSubscriber = new OperationSubscriber<>();
    collection.drop().subscribe(successSubscriber);
    successSubscriber.await();
    // make a document and insert it
    final Person ada = new Person("Ada Byron", 20, new Address("St James Square", "London", "W1"));
    System.out.println("Original Person Model: " + ada);
    ObservableSubscriber<InsertOneResult> insertOneSubscriber = new OperationSubscriber<>();
    collection.insertOne(ada).subscribe(insertOneSubscriber);
    insertOneSubscriber.await();
    // get it (since it's the only one in there since we dropped the rest earlier on)
    ObservableSubscriber<Person> personSubscriber = new PrintToStringSubscriber<>();
    collection.find().first().subscribe(personSubscriber);
    personSubscriber.await();
    // now, lets add some more people so we can explore queries and cursors
    List<Person> people = asList(new Person("Charles Babbage", 45, new Address("5 Devonshire Street", "London", "W11")), new Person("Alan Turing", 28, new Address("Bletchley Hall", "Bletchley Park", "MK12")), new Person("Timothy Berners-Lee", 61, new Address("Colehill", "Wimborne", null)));
    ObservableSubscriber<InsertManyResult> insertManySubscriber = new OperationSubscriber<>();
    collection.insertMany(people).subscribe(insertManySubscriber);
    insertManySubscriber.await();
    // get all the documents in the collection and print them out
    personSubscriber = new PrintToStringSubscriber<>();
    collection.find().subscribe(personSubscriber);
    personSubscriber.await();
    // now use a query to get 1 document out
    personSubscriber = new PrintToStringSubscriber<>();
    collection.find(eq("address.city", "Wimborne")).first().subscribe(personSubscriber);
    personSubscriber.await();
    // now lets find every over 30
    personSubscriber = new PrintToStringSubscriber<>();
    collection.find(gt("age", 30)).subscribe(personSubscriber);
    personSubscriber.await();
    // Update One
    ObservableSubscriber<UpdateResult> updateSubscriber = new OperationSubscriber<>();
    collection.updateOne(eq("name", "Ada Byron"), combine(set("age", 23), set("name", "Ada Lovelace"))).subscribe(updateSubscriber);
    updateSubscriber.await();
    // Update Many
    updateSubscriber = new OperationSubscriber<>();
    collection.updateMany(not(eq("zip", null)), set("zip", null)).subscribe(updateSubscriber);
    updateSubscriber.await();
    // Replace One
    updateSubscriber = new OperationSubscriber<>();
    collection.replaceOne(eq("name", "Ada Lovelace"), ada).subscribe(updateSubscriber);
    updateSubscriber.await();
    // Delete One
    ObservableSubscriber<DeleteResult> deleteSubscriber = new OperationSubscriber<>();
    collection.deleteOne(eq("address.city", "Wimborne")).subscribe(deleteSubscriber);
    deleteSubscriber.await();
    // Delete Many
    deleteSubscriber = new OperationSubscriber<>();
    collection.deleteMany(eq("address.city", "London")).subscribe(deleteSubscriber);
    deleteSubscriber.await();
    // Clean up
    successSubscriber = new OperationSubscriber<>();
    database.drop().subscribe(successSubscriber);
    successSubscriber.await();
    // release resources
    mongoClient.close();
}
Also used : OperationSubscriber(reactivestreams.helpers.SubscriberHelpers.OperationSubscriber) InsertManyResult(com.mongodb.client.result.InsertManyResult) MongoClient(com.mongodb.reactivestreams.client.MongoClient) InsertOneResult(com.mongodb.client.result.InsertOneResult) CodecRegistry(org.bson.codecs.configuration.CodecRegistry) PrintToStringSubscriber(reactivestreams.helpers.SubscriberHelpers.PrintToStringSubscriber) UpdateResult(com.mongodb.client.result.UpdateResult) DeleteResult(com.mongodb.client.result.DeleteResult) MongoDatabase(com.mongodb.reactivestreams.client.MongoDatabase)

Example 5 with InsertOneResult

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

the class GridFSUploadPublisherImpl method createSaveChunksMono.

private Mono<Long> createSaveChunksMono(final AtomicBoolean terminated) {
    return Mono.create(sink -> {
        final AtomicLong lengthInBytes = new AtomicLong(0);
        final AtomicInteger chunkIndex = new AtomicInteger(0);
        new ResizingByteBufferFlux(source, chunkSizeBytes).flatMap((Function<ByteBuffer, Publisher<InsertOneResult>>) byteBuffer -> {
            if (terminated.get()) {
                return Mono.empty();
            }
            byte[] byteArray = new byte[byteBuffer.remaining()];
            if (byteBuffer.hasArray()) {
                System.arraycopy(byteBuffer.array(), byteBuffer.position(), byteArray, 0, byteBuffer.remaining());
            } else {
                byteBuffer.mark();
                byteBuffer.get(byteArray);
                byteBuffer.reset();
            }
            Binary data = new Binary(byteArray);
            lengthInBytes.addAndGet(data.length());
            Document chunkDocument = new Document("files_id", fileId).append("n", chunkIndex.getAndIncrement()).append("data", data);
            return clientSession == null ? chunksCollection.insertOne(chunkDocument) : chunksCollection.insertOne(clientSession, chunkDocument);
        }).subscribe(null, sink::error, () -> sink.success(lengthInBytes.get()));
    });
}
Also used : Function(java.util.function.Function) AtomicLong(java.util.concurrent.atomic.AtomicLong) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Binary(org.bson.types.Binary) InsertOneResult(com.mongodb.client.result.InsertOneResult) Document(org.bson.Document)

Aggregations

InsertOneResult (com.mongodb.client.result.InsertOneResult)15 Document (org.bson.Document)13 OperationSubscriber (reactivestreams.helpers.SubscriberHelpers.OperationSubscriber)9 MongoClient (com.mongodb.reactivestreams.client.MongoClient)7 MongoClientSettings (com.mongodb.MongoClientSettings)5 DataKeyOptions (com.mongodb.client.model.vault.DataKeyOptions)4 SecureRandom (java.security.SecureRandom)4 HashMap (java.util.HashMap)4 Map (java.util.Map)4 BsonBinary (org.bson.BsonBinary)4 BsonDocument (org.bson.BsonDocument)4 BsonString (org.bson.BsonString)4 ClientEncryptionSettings (com.mongodb.ClientEncryptionSettings)3 ConnectionString (com.mongodb.ConnectionString)3 EncryptOptions (com.mongodb.client.model.vault.EncryptOptions)3 InsertManyResult (com.mongodb.client.result.InsertManyResult)3 Test (org.junit.Test)3 PrintDocumentSubscriber (reactivestreams.helpers.SubscriberHelpers.PrintDocumentSubscriber)3 AutoEncryptionSettings (com.mongodb.AutoEncryptionSettings)2 MongoNamespace (com.mongodb.MongoNamespace)2