Search in sources :

Example 6 with InsertOneResult

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

the class MongoCollectionImplTest method testInsertOne.

@Test
public void testInsertOne() {
    InsertOneOptions options = new InsertOneOptions().bypassDocumentValidation(true);
    Document insert = new Document("_id", 1);
    assertAll("insertOne", () -> assertAll("check validation", () -> assertThrows(IllegalArgumentException.class, () -> collection.insertOne(null)), () -> assertThrows(IllegalArgumentException.class, () -> collection.insertOne(insert, null)), () -> assertThrows(IllegalArgumentException.class, () -> collection.insertOne(clientSession, null)), () -> assertThrows(IllegalArgumentException.class, () -> collection.insertOne(clientSession, insert, null)), () -> assertThrows(IllegalArgumentException.class, () -> collection.insertOne(null, insert)), () -> assertThrows(IllegalArgumentException.class, () -> collection.insertOne(null, insert, options))), () -> {
        Publisher<InsertOneResult> expected = mongoOperationPublisher.insertOne(null, insert, new InsertOneOptions());
        assertPublisherIsTheSameAs(expected, collection.insertOne(insert), "Default");
    }, () -> {
        Publisher<InsertOneResult> expected = mongoOperationPublisher.insertOne(null, insert, options);
        assertPublisherIsTheSameAs(expected, collection.insertOne(insert, options), "With options");
    }, () -> {
        Publisher<InsertOneResult> expected = mongoOperationPublisher.insertOne(clientSession, insert, new InsertOneOptions());
        assertPublisherIsTheSameAs(expected, collection.insertOne(clientSession, insert), "With client session");
    }, () -> {
        Publisher<InsertOneResult> expected = mongoOperationPublisher.insertOne(clientSession, insert, options);
        assertPublisherIsTheSameAs(expected, collection.insertOne(clientSession, insert, options), "With client session & options");
    });
}
Also used : InsertOneOptions(com.mongodb.client.model.InsertOneOptions) Document(org.bson.Document) BsonDocument(org.bson.BsonDocument) InsertOneResult(com.mongodb.client.result.InsertOneResult) Test(org.junit.jupiter.api.Test)

Example 7 with InsertOneResult

use of com.mongodb.client.result.InsertOneResult in project spring-data-mongodb by spring-projects.

the class ReactiveMongoTemplate method insertDocument.

protected Mono<Object> insertDocument(String collectionName, Document dbDoc, Class<?> entityClass) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(String.format("Inserting Document containing fields: " + dbDoc.keySet() + " in collection: " + collectionName));
    }
    Document document = new Document(dbDoc);
    Flux<InsertOneResult> execute = execute(collectionName, collection -> {
        MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.INSERT, collectionName, entityClass, dbDoc, null);
        WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
        MongoCollection<Document> collectionToUse = prepareCollection(collection, writeConcernToUse);
        return collectionToUse.insertOne(document);
    });
    return Flux.from(execute).last().map(success -> MappedDocument.of(document).getId());
}
Also used : WriteConcern(com.mongodb.WriteConcern) Document(org.bson.Document) FullDocument(com.mongodb.client.model.changestream.FullDocument) InsertOneResult(com.mongodb.client.result.InsertOneResult)

Example 8 with InsertOneResult

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

the class ClientSideEncryptionAutoEncryptionSettingsTour method main.

/**
 * Run this main method to see the output of this quick example.
 *
 * Requires the mongodb-crypt library in the class path and mongocryptd on the system path.
 *
 * @param args ignored args
 */
public static void main(final String[] args) {
    // This would have to be the same master key as was used to create the encryption key
    final byte[] localMasterKey = new byte[96];
    new SecureRandom().nextBytes(localMasterKey);
    Map<String, Map<String, Object>> kmsProviders = new HashMap<String, Map<String, Object>>() {

        {
            put("local", new HashMap<String, Object>() {

                {
                    put("key", localMasterKey);
                }
            });
        }
    };
    String keyVaultNamespace = "admin.datakeys";
    ClientEncryptionSettings clientEncryptionSettings = ClientEncryptionSettings.builder().keyVaultMongoClientSettings(MongoClientSettings.builder().applyConnectionString(new ConnectionString("mongodb://localhost")).build()).keyVaultNamespace(keyVaultNamespace).kmsProviders(kmsProviders).build();
    ClientEncryption clientEncryption = ClientEncryptions.create(clientEncryptionSettings);
    ObservableSubscriber<BsonBinary> dataKeySubscriber = new OperationSubscriber<>();
    clientEncryption.createDataKey("local", new DataKeyOptions()).subscribe(dataKeySubscriber);
    dataKeySubscriber.await();
    String base64DataKeyId = Base64.getEncoder().encodeToString(dataKeySubscriber.getReceived().get(0).getData());
    final String dbName = "test";
    final String collName = "coll";
    AutoEncryptionSettings autoEncryptionSettings = AutoEncryptionSettings.builder().keyVaultNamespace(keyVaultNamespace).kmsProviders(kmsProviders).schemaMap(new HashMap<String, BsonDocument>() {

        {
            put(dbName + "." + collName, // Need a schema that references the new data key
            BsonDocument.parse("{" + "  properties: {" + "    encryptedField: {" + "      encrypt: {" + "        keyId: [{" + "          \"$binary\": {" + "            \"base64\": \"" + base64DataKeyId + "\"," + "            \"subType\": \"04\"" + "          }" + "        }]," + "        bsonType: \"string\"," + "        algorithm: \"AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic\"" + "      }" + "    }" + "  }," + "  \"bsonType\": \"object\"" + "}"));
        }
    }).build();
    MongoClientSettings clientSettings = MongoClientSettings.builder().autoEncryptionSettings(autoEncryptionSettings).build();
    MongoClient mongoClient = MongoClients.create(clientSettings);
    MongoCollection<Document> collection = mongoClient.getDatabase("test").getCollection("coll");
    ObservableSubscriber<Void> successSubscriber = new OperationSubscriber<>();
    collection.drop().subscribe(successSubscriber);
    successSubscriber.await();
    ObservableSubscriber<InsertOneResult> insertOneSubscriber = new OperationSubscriber<>();
    collection.insertOne(new Document("encryptedField", "123456789")).subscribe(insertOneSubscriber);
    insertOneSubscriber.await();
    ObservableSubscriber<Document> documentSubscriber = new PrintDocumentSubscriber();
    collection.find().first().subscribe(documentSubscriber);
    documentSubscriber.await();
    // release resources
    mongoClient.close();
}
Also used : PrintDocumentSubscriber(reactivestreams.helpers.SubscriberHelpers.PrintDocumentSubscriber) HashMap(java.util.HashMap) ClientEncryption(com.mongodb.reactivestreams.client.vault.ClientEncryption) ConnectionString(com.mongodb.ConnectionString) Document(org.bson.Document) BsonDocument(org.bson.BsonDocument) DataKeyOptions(com.mongodb.client.model.vault.DataKeyOptions) MongoClient(com.mongodb.reactivestreams.client.MongoClient) ClientEncryptionSettings(com.mongodb.ClientEncryptionSettings) InsertOneResult(com.mongodb.client.result.InsertOneResult) BsonBinary(org.bson.BsonBinary) OperationSubscriber(reactivestreams.helpers.SubscriberHelpers.OperationSubscriber) SecureRandom(java.security.SecureRandom) MongoClientSettings(com.mongodb.MongoClientSettings) AutoEncryptionSettings(com.mongodb.AutoEncryptionSettings) ConnectionString(com.mongodb.ConnectionString) HashMap(java.util.HashMap) Map(java.util.Map)

Example 9 with InsertOneResult

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

the class ClientSideEncryptionExplicitEncryptionOnlyTour method main.

/**
 * Run this main method to see the output of this quick example.
 *
 * Requires the mongodb-crypt library in the class path and mongocryptd on the system path.
 * Assumes the schema has already been created in MongoDB.
 *
 * @param args ignored args
 */
public static void main(final String[] args) {
    // This would have to be the same master key as was used to create the encryption key
    final byte[] localMasterKey = new byte[96];
    new SecureRandom().nextBytes(localMasterKey);
    Map<String, Map<String, Object>> kmsProviders = new HashMap<String, Map<String, Object>>() {

        {
            put("local", new HashMap<String, Object>() {

                {
                    put("key", localMasterKey);
                }
            });
        }
    };
    MongoNamespace keyVaultNamespace = new MongoNamespace("encryption.testKeyVault");
    MongoClientSettings clientSettings = MongoClientSettings.builder().autoEncryptionSettings(AutoEncryptionSettings.builder().keyVaultNamespace(keyVaultNamespace.getFullName()).kmsProviders(kmsProviders).bypassAutoEncryption(true).build()).build();
    MongoClient mongoClient = MongoClients.create(clientSettings);
    // Set up the key vault for this example
    MongoCollection<Document> keyVaultCollection = mongoClient.getDatabase(keyVaultNamespace.getDatabaseName()).getCollection(keyVaultNamespace.getCollectionName());
    ObservableSubscriber<Void> successSubscriber = new OperationSubscriber<>();
    keyVaultCollection.drop().subscribe(successSubscriber);
    successSubscriber.await();
    // Ensure that two data keys cannot share the same keyAltName.
    ObservableSubscriber<String> indexSubscriber = new OperationSubscriber<>();
    keyVaultCollection.createIndex(Indexes.ascending("keyAltNames"), new IndexOptions().unique(true).partialFilterExpression(Filters.exists("keyAltNames"))).subscribe(indexSubscriber);
    indexSubscriber.await();
    MongoCollection<Document> collection = mongoClient.getDatabase("test").getCollection("coll");
    successSubscriber = new OperationSubscriber<>();
    collection.drop().subscribe(successSubscriber);
    successSubscriber.await();
    // Create the ClientEncryption instance
    ClientEncryptionSettings clientEncryptionSettings = ClientEncryptionSettings.builder().keyVaultMongoClientSettings(MongoClientSettings.builder().applyConnectionString(new ConnectionString("mongodb://localhost")).build()).keyVaultNamespace(keyVaultNamespace.getFullName()).kmsProviders(kmsProviders).build();
    ClientEncryption clientEncryption = ClientEncryptions.create(clientEncryptionSettings);
    BsonBinary dataKeyId = clientEncryption.createDataKey("local", new DataKeyOptions());
    // Explicitly encrypt a field
    BsonBinary encryptedFieldValue = clientEncryption.encrypt(new BsonString("123456789"), new EncryptOptions("AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic").keyId(dataKeyId));
    ObservableSubscriber<InsertOneResult> insertOneSubscriber = new OperationSubscriber<>();
    collection.insertOne(new Document("encryptedField", encryptedFieldValue)).subscribe(insertOneSubscriber);
    insertOneSubscriber.await();
    ObservableSubscriber<Document> documentSubscriber = new OperationSubscriber<>();
    collection.find().first().subscribe(documentSubscriber);
    Document doc = documentSubscriber.get().get(0);
    System.out.println(doc.toJson());
    // release resources
    clientEncryption.close();
    mongoClient.close();
}
Also used : HashMap(java.util.HashMap) ClientEncryption(com.mongodb.client.vault.ClientEncryption) BsonString(org.bson.BsonString) ConnectionString(com.mongodb.ConnectionString) Document(org.bson.Document) DataKeyOptions(com.mongodb.client.model.vault.DataKeyOptions) MongoClient(com.mongodb.reactivestreams.client.MongoClient) ClientEncryptionSettings(com.mongodb.ClientEncryptionSettings) EncryptOptions(com.mongodb.client.model.vault.EncryptOptions) InsertOneResult(com.mongodb.client.result.InsertOneResult) IndexOptions(com.mongodb.client.model.IndexOptions) OperationSubscriber(reactivestreams.helpers.SubscriberHelpers.OperationSubscriber) BsonBinary(org.bson.BsonBinary) SecureRandom(java.security.SecureRandom) MongoClientSettings(com.mongodb.MongoClientSettings) MongoNamespace(com.mongodb.MongoNamespace) BsonString(org.bson.BsonString) ConnectionString(com.mongodb.ConnectionString) HashMap(java.util.HashMap) Map(java.util.Map)

Example 10 with InsertOneResult

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

the class QuickTour 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]);
    }
    // get handle to "mydb" database
    MongoDatabase database = mongoClient.getDatabase("mydb");
    // get a handle to the "test" collection
    final MongoCollection<Document> collection = database.getCollection("test");
    // drop all the data in it
    ObservableSubscriber<Void> successSubscriber = new OperationSubscriber<>();
    collection.drop().subscribe(successSubscriber);
    successSubscriber.await();
    // make a document and insert it
    Document doc = new Document("name", "MongoDB").append("type", "database").append("count", 1).append("info", new Document("x", 203).append("y", 102));
    ObservableSubscriber<InsertOneResult> insertOneSubscriber = new OperationSubscriber<>();
    collection.insertOne(doc).subscribe(insertOneSubscriber);
    insertOneSubscriber.await();
    // get it (since it's the only one in there since we dropped the rest earlier on)
    ObservableSubscriber<Document> documentSubscriber = new PrintDocumentSubscriber();
    collection.find().first().subscribe(documentSubscriber);
    documentSubscriber.await();
    // now, lets add lots of little documents to the collection so we can explore queries and cursors
    List<Document> documents = new ArrayList<>();
    for (int i = 0; i < 100; i++) {
        documents.add(new Document("i", i));
    }
    ObservableSubscriber<InsertManyResult> insertManySubscriber = new OperationSubscriber<>();
    collection.insertMany(documents).subscribe(insertManySubscriber);
    insertManySubscriber.await();
    // find first
    documentSubscriber = new PrintDocumentSubscriber();
    collection.find().first().subscribe(documentSubscriber);
    documentSubscriber.await();
    // lets get all the documents in the collection and print them out
    documentSubscriber = new PrintDocumentSubscriber();
    collection.find().subscribe(documentSubscriber);
    documentSubscriber.await();
    // Query Filters
    // now use a query to get 1 document out
    documentSubscriber = new PrintDocumentSubscriber();
    collection.find(eq("i", 71)).first().subscribe(documentSubscriber);
    documentSubscriber.await();
    // now use a range query to get a larger subset
    documentSubscriber = new PrintDocumentSubscriber();
    collection.find(gt("i", 50)).subscribe(documentSubscriber);
    successSubscriber.await();
    // range query with multiple constraints
    documentSubscriber = new PrintDocumentSubscriber();
    collection.find(and(gt("i", 50), lte("i", 100))).subscribe(documentSubscriber);
    successSubscriber.await();
    // Sorting
    documentSubscriber = new PrintDocumentSubscriber();
    collection.find(exists("i")).sort(descending("i")).first().subscribe(documentSubscriber);
    documentSubscriber.await();
    // Projection
    documentSubscriber = new PrintDocumentSubscriber();
    collection.find().projection(excludeId()).first().subscribe(documentSubscriber);
    documentSubscriber.await();
    // Aggregation
    documentSubscriber = new PrintDocumentSubscriber();
    collection.aggregate(asList(match(gt("i", 0)), project(Document.parse("{ITimes10: {$multiply: ['$i', 10]}}")))).subscribe(documentSubscriber);
    documentSubscriber.await();
    documentSubscriber = new PrintDocumentSubscriber();
    collection.aggregate(singletonList(group(null, sum("total", "$i")))).first().subscribe(documentSubscriber);
    documentSubscriber.await();
    // Update One
    ObservableSubscriber<UpdateResult> updateSubscriber = new OperationSubscriber<>();
    collection.updateOne(eq("i", 10), set("i", 110)).subscribe(updateSubscriber);
    updateSubscriber.await();
    // Update Many
    updateSubscriber = new OperationSubscriber<>();
    collection.updateMany(lt("i", 100), inc("i", 100)).subscribe(updateSubscriber);
    updateSubscriber.await();
    // Delete One
    ObservableSubscriber<DeleteResult> deleteSubscriber = new OperationSubscriber<>();
    collection.deleteOne(eq("i", 110)).subscribe(deleteSubscriber);
    deleteSubscriber.await();
    // Delete Many
    deleteSubscriber = new OperationSubscriber<>();
    collection.deleteMany(gte("i", 100)).subscribe(deleteSubscriber);
    deleteSubscriber.await();
    // Create Index
    OperationSubscriber<String> createIndexSubscriber = new PrintSubscriber<>("Create Index Result: %s");
    collection.createIndex(new Document("i", 1)).subscribe(createIndexSubscriber);
    createIndexSubscriber.await();
    // Clean up
    successSubscriber = new OperationSubscriber<>();
    collection.drop().subscribe(successSubscriber);
    successSubscriber.await();
    // release resources
    mongoClient.close();
}
Also used : PrintDocumentSubscriber(reactivestreams.helpers.SubscriberHelpers.PrintDocumentSubscriber) OperationSubscriber(reactivestreams.helpers.SubscriberHelpers.OperationSubscriber) ArrayList(java.util.ArrayList) Document(org.bson.Document) InsertManyResult(com.mongodb.client.result.InsertManyResult) MongoClient(com.mongodb.reactivestreams.client.MongoClient) PrintSubscriber(reactivestreams.helpers.SubscriberHelpers.PrintSubscriber) InsertOneResult(com.mongodb.client.result.InsertOneResult) UpdateResult(com.mongodb.client.result.UpdateResult) DeleteResult(com.mongodb.client.result.DeleteResult) MongoDatabase(com.mongodb.reactivestreams.client.MongoDatabase)

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