Search in sources :

Example 1 with InsertManyResult

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

the class JsonPoweredCrudTestHelper method getInsertManyResult.

BsonDocument getInsertManyResult(final BsonDocument collectionOptions, final BsonDocument arguments, @Nullable final ClientSession clientSession) {
    List<BsonDocument> documents = new ArrayList<>();
    for (BsonValue document : arguments.getArray("documents")) {
        documents.add(document.asDocument());
    }
    try {
        InsertManyOptions options = new InsertManyOptions().ordered(arguments.getDocument("options", new BsonDocument()).getBoolean("ordered", BsonBoolean.TRUE).getValue());
        if (arguments.containsKey("bypassDocumentValidation")) {
            options.bypassDocumentValidation(arguments.getBoolean("bypassDocumentValidation").getValue());
        }
        InsertManyResult insertManyResult;
        if (clientSession == null) {
            insertManyResult = getCollection(collectionOptions).insertMany(documents, options);
        } else {
            insertManyResult = getCollection(collectionOptions).insertMany(clientSession, documents, options);
        }
        BsonDocument insertedIds = new BsonDocument();
        insertManyResult.getInsertedIds().forEach((i, v) -> insertedIds.put(i.toString(), v));
        return toResult(new BsonDocument("insertedIds", insertedIds));
    } catch (MongoBulkWriteException e) {
        // For transaction tests, the exception is expected to be returned.
        if (clientSession != null && clientSession.hasActiveTransaction()) {
            throw e;
        }
        // Test results are expecting this to look just like bulkWrite error, so translate to InsertOneModel so the result
        // translation code can be reused.
        List<InsertOneModel<BsonDocument>> writeModels = new ArrayList<InsertOneModel<BsonDocument>>();
        for (BsonValue document : arguments.getArray("documents")) {
            writeModels.add(new InsertOneModel<>(document.asDocument()));
        }
        BsonDocument result = toResult(e.getWriteResult(), writeModels, e.getWriteErrors());
        result.put("error", BsonBoolean.TRUE);
        return result;
    }
}
Also used : InsertOneModel(com.mongodb.client.model.InsertOneModel) BsonDocument(org.bson.BsonDocument) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) MongoBulkWriteException(com.mongodb.MongoBulkWriteException) BsonValue(org.bson.BsonValue) InsertManyOptions(com.mongodb.client.model.InsertManyOptions) InsertManyResult(com.mongodb.client.result.InsertManyResult)

Example 2 with InsertManyResult

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

the class MongoCollectionTest method bulkInsertRawBsonDocuments.

@Test
public void bulkInsertRawBsonDocuments() {
    // given
    List<RawBsonDocument> docs = asList(RawBsonDocument.parse("{a: 1}"), RawBsonDocument.parse("{a: 2}"));
    // when
    InsertManyResult result = collection.withDocumentClass(RawBsonDocument.class).insertMany(docs);
    // then
    Map<Integer, BsonValue> expectedResult = new HashMap<>();
    expectedResult.put(0, null);
    expectedResult.put(1, null);
    assertEquals(expectedResult, result.getInsertedIds());
}
Also used : HashMap(java.util.HashMap) RawBsonDocument(org.bson.RawBsonDocument) InsertManyResult(com.mongodb.client.result.InsertManyResult) BsonValue(org.bson.BsonValue) ClusterFixture.isServerlessTest(com.mongodb.ClusterFixture.isServerlessTest) Test(org.junit.Test)

Example 3 with InsertManyResult

use of com.mongodb.client.result.InsertManyResult 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 4 with InsertManyResult

use of com.mongodb.client.result.InsertManyResult in project morphia by mongodb.

the class FiltersTest method testRand.

@Test
public void testRand() {
    checkMinServerVersion(Version.valueOf("4.4.2"));
    int count = 100;
    List<Document> list = new ArrayList<>();
    for (int i = 0; i < count; i++) {
        list.add(new Document("_id", i).append("r", 0));
    }
    String collectionName = "rand";
    InsertManyResult bulk = getDatabase().getCollection(collectionName).insertMany(list, new InsertManyOptions().ordered(false));
    assertEquals(bulk.getInsertedIds().size(), count);
    long matches = getDs().find(collectionName, Document.class).filter(expr(ComparisonExpressions.lt(value(0.5), rand()))).count();
    assertTrue(matches < 100);
}
Also used : ArrayList(java.util.ArrayList) Document(org.bson.Document) InsertManyResult(com.mongodb.client.result.InsertManyResult) InsertManyOptions(com.mongodb.client.model.InsertManyOptions) Test(org.testng.annotations.Test)

Example 5 with InsertManyResult

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

the class MongoCollectionImplTest method testInsertMany.

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

Aggregations

InsertManyResult (com.mongodb.client.result.InsertManyResult)9 Document (org.bson.Document)6 InsertManyOptions (com.mongodb.client.model.InsertManyOptions)4 ArrayList (java.util.ArrayList)4 OperationSubscriber (reactivestreams.helpers.SubscriberHelpers.OperationSubscriber)4 InsertOneResult (com.mongodb.client.result.InsertOneResult)3 Test (org.junit.Test)3 DeleteResult (com.mongodb.client.result.DeleteResult)2 UpdateResult (com.mongodb.client.result.UpdateResult)2 MongoClient (com.mongodb.reactivestreams.client.MongoClient)2 MongoDatabase (com.mongodb.reactivestreams.client.MongoDatabase)2 BsonDocument (org.bson.BsonDocument)2 BsonValue (org.bson.BsonValue)2 Test (org.testng.annotations.Test)2 ClusterFixture.isServerlessTest (com.mongodb.ClusterFixture.isServerlessTest)1 MongoBulkWriteException (com.mongodb.MongoBulkWriteException)1 InsertOneModel (com.mongodb.client.model.InsertOneModel)1 HashMap (java.util.HashMap)1 List (java.util.List)1 RawBsonDocument (org.bson.RawBsonDocument)1