Search in sources :

Example 6 with UpdateResult

use of com.mongodb.client.result.UpdateResult in project camel by apache.

the class MongoDbOperationsTest method testUpdateFromString.

@Test
public void testUpdateFromString() throws Exception {
    // Prepare test
    assertEquals(0, testCollection.count());
    for (int i = 1; i <= 100; i++) {
        String body = null;
        try (Formatter f = new Formatter()) {
            if (i % 2 == 0) {
                body = f.format("{\"_id\":\"testSave%d\", \"scientist\":\"Einstein\"}", i).toString();
            } else {
                body = f.format("{\"_id\":\"testSave%d\", \"scientist\":\"Einstein\", \"extraField\": true}", i).toString();
            }
            f.close();
        }
        template.requestBody("direct:insert", body);
    }
    assertEquals(100L, testCollection.count());
    // Testing the update logic
    Bson extraField = eq("extraField", true);
    assertEquals("Number of records with 'extraField' flag on must equal 50", 50L, testCollection.count(extraField));
    assertEquals("Number of records with 'scientist' field = Darwin on must equal 0", 0, testCollection.count(new Document("scientist", "Darwin")));
    Bson updateObj = combine(set("scientist", "Darwin"), currentTimestamp("lastModified"));
    String updates = "[" + extraField.toBsonDocument(Document.class, MongoClient.getDefaultCodecRegistry()).toJson() + "," + updateObj.toBsonDocument(Document.class, MongoClient.getDefaultCodecRegistry()).toJson() + "]";
    Exchange resultExchange = template.request("direct:update", new Processor() {

        @Override
        public void process(Exchange exchange) throws Exception {
            exchange.getIn().setBody(updates);
            exchange.getIn().setHeader(MongoDbConstants.MULTIUPDATE, true);
        }
    });
    Object result = resultExchange.getOut().getBody();
    assertTrue(result instanceof UpdateResult);
    assertEquals("Number of records updated header should equal 50", 50L, resultExchange.getOut().getHeader(MongoDbConstants.RECORDS_AFFECTED));
    assertEquals("Number of records with 'scientist' field = Darwin on must equal 50 after update", 50, testCollection.count(new Document("scientist", "Darwin")));
}
Also used : Exchange(org.apache.camel.Exchange) Processor(org.apache.camel.Processor) Formatter(java.util.Formatter) Document(org.bson.Document) UpdateResult(com.mongodb.client.result.UpdateResult) Bson(org.bson.conversions.Bson) Test(org.junit.Test)

Example 7 with UpdateResult

use of com.mongodb.client.result.UpdateResult in project YCSB by brianfrankcooper.

the class MongoDbClient method update.

/**
   * Update a record in the database. Any field/value pairs in the specified
   * values HashMap will be written into the record with the specified record
   * key, overwriting any existing values with the same field name.
   * 
   * @param table
   *          The name of the table
   * @param key
   *          The record key of the record to write.
   * @param values
   *          A HashMap of field/value pairs to update in the record
   * @return Zero on success, a non-zero error code on error. See this class's
   *         description for a discussion of error codes.
   */
@Override
public Status update(String table, String key, HashMap<String, ByteIterator> values) {
    try {
        MongoCollection<Document> collection = database.getCollection(table);
        Document query = new Document("_id", key);
        Document fieldsToSet = new Document();
        for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
            fieldsToSet.put(entry.getKey(), entry.getValue().toArray());
        }
        Document update = new Document("$set", fieldsToSet);
        UpdateResult result = collection.updateOne(query, update);
        if (result.wasAcknowledged() && result.getMatchedCount() == 0) {
            System.err.println("Nothing updated for key " + key);
            return Status.NOT_FOUND;
        }
        return Status.OK;
    } catch (Exception e) {
        System.err.println(e.toString());
        return Status.ERROR;
    }
}
Also used : ByteArrayByteIterator(com.yahoo.ycsb.ByteArrayByteIterator) ByteIterator(com.yahoo.ycsb.ByteIterator) Document(org.bson.Document) HashMap(java.util.HashMap) Map(java.util.Map) UpdateResult(com.mongodb.client.result.UpdateResult) DBException(com.yahoo.ycsb.DBException)

Example 8 with UpdateResult

use of com.mongodb.client.result.UpdateResult 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 = new MongoClient();
    } else {
        mongoClient = new MongoClient(new MongoClientURI(args[0]));
    }
    // get handle to "mydb" database
    MongoDatabase database = mongoClient.getDatabase("mydb");
    // get a handle to the "test" collection
    MongoCollection<Document> collection = database.getCollection("test");
    // drop all the data in it
    collection.drop();
    // 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));
    collection.insertOne(doc);
    // get it (since it's the only one in there since we dropped the rest earlier on)
    Document myDoc = collection.find().first();
    System.out.println(myDoc.toJson());
    // now, lets add lots of little documents to the collection so we can explore queries and cursors
    List<Document> documents = new ArrayList<Document>();
    for (int i = 0; i < 100; i++) {
        documents.add(new Document("i", i));
    }
    collection.insertMany(documents);
    System.out.println("total # of documents after inserting 100 small ones (should be 101) " + collection.count());
    // find first
    myDoc = collection.find().first();
    System.out.println(myDoc.toJson());
    // lets get all the documents in the collection and print them out
    MongoCursor<Document> cursor = collection.find().iterator();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }
    for (Document cur : collection.find()) {
        System.out.println(cur.toJson());
    }
    // now use a query to get 1 document out
    myDoc = collection.find(eq("i", 71)).first();
    System.out.println(myDoc.toJson());
    // now use a range query to get a larger subset
    cursor = collection.find(gt("i", 50)).iterator();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }
    // range query with multiple constraints
    cursor = collection.find(and(gt("i", 50), lte("i", 100))).iterator();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }
    // Query Filters
    myDoc = collection.find(eq("i", 71)).first();
    System.out.println(myDoc.toJson());
    // now use a range query to get a larger subset
    Block<Document> printBlock = new Block<Document>() {

        @Override
        public void apply(final Document document) {
            System.out.println(document.toJson());
        }
    };
    collection.find(gt("i", 50)).forEach(printBlock);
    // filter where; 50 < i <= 100
    collection.find(and(gt("i", 50), lte("i", 100))).forEach(printBlock);
    // Sorting
    myDoc = collection.find(exists("i")).sort(descending("i")).first();
    System.out.println(myDoc.toJson());
    // Projection
    myDoc = collection.find().projection(excludeId()).first();
    System.out.println(myDoc.toJson());
    // Aggregation
    collection.aggregate(asList(match(gt("i", 0)), project(Document.parse("{ITimes10: {$multiply: ['$i', 10]}}")))).forEach(printBlock);
    myDoc = collection.aggregate(singletonList(group(null, sum("total", "$i")))).first();
    System.out.println(myDoc.toJson());
    // Update One
    collection.updateOne(eq("i", 10), set("i", 110));
    // Update Many
    UpdateResult updateResult = collection.updateMany(lt("i", 100), inc("i", 100));
    System.out.println(updateResult.getModifiedCount());
    // Delete One
    collection.deleteOne(eq("i", 110));
    // Delete Many
    DeleteResult deleteResult = collection.deleteMany(gte("i", 100));
    System.out.println(deleteResult.getDeletedCount());
    collection.drop();
    // ordered bulk writes
    List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>();
    writes.add(new InsertOneModel<Document>(new Document("_id", 4)));
    writes.add(new InsertOneModel<Document>(new Document("_id", 5)));
    writes.add(new InsertOneModel<Document>(new Document("_id", 6)));
    writes.add(new UpdateOneModel<Document>(new Document("_id", 1), new Document("$set", new Document("x", 2))));
    writes.add(new DeleteOneModel<Document>(new Document("_id", 2)));
    writes.add(new ReplaceOneModel<Document>(new Document("_id", 3), new Document("_id", 3).append("x", 4)));
    collection.bulkWrite(writes);
    collection.drop();
    collection.bulkWrite(writes, new BulkWriteOptions().ordered(false));
    //collection.find().forEach(printBlock);
    // Clean up
    database.drop();
    // release resources
    mongoClient.close();
}
Also used : MongoClientURI(com.mongodb.MongoClientURI) ArrayList(java.util.ArrayList) Document(org.bson.Document) WriteModel(com.mongodb.client.model.WriteModel) MongoClient(com.mongodb.MongoClient) BulkWriteOptions(com.mongodb.client.model.BulkWriteOptions) Block(com.mongodb.Block) UpdateResult(com.mongodb.client.result.UpdateResult) DeleteResult(com.mongodb.client.result.DeleteResult) MongoDatabase(com.mongodb.client.MongoDatabase)

Example 9 with UpdateResult

use of com.mongodb.client.result.UpdateResult in project drill by apache.

the class MongoPersistentStore method putIfAbsent.

@Override
public boolean putIfAbsent(String key, V value) {
    try {
        Bson query = Filters.eq(DrillMongoConstants.ID, key);
        Bson update = Updates.set(pKey, bytes(value));
        UpdateResult updateResult = collection.updateOne(query, update, new UpdateOptions().upsert(true));
        return updateResult.getModifiedCount() == 1;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new DrillRuntimeException(e.getMessage(), e);
    }
}
Also used : DrillRuntimeException(org.apache.drill.common.exceptions.DrillRuntimeException) UpdateResult(com.mongodb.client.result.UpdateResult) UpdateOptions(com.mongodb.client.model.UpdateOptions) IOException(java.io.IOException) DrillRuntimeException(org.apache.drill.common.exceptions.DrillRuntimeException) NoSuchElementException(java.util.NoSuchElementException) Bson(org.bson.conversions.Bson)

Example 10 with UpdateResult

use of com.mongodb.client.result.UpdateResult in project camel by apache.

the class MongoDbOperationsTest method testSave.

@Test
public void testSave() throws Exception {
    // Prepare test
    assertEquals(0, testCollection.count());
    Object[] req = new Object[] { new Document(MONGO_ID, "testSave1").append("scientist", "Einstein").toJson(), new Document(MONGO_ID, "testSave2").append("scientist", "Copernicus").toJson() };
    Object result = template.requestBody("direct:insert", req);
    assertTrue(result instanceof List);
    assertEquals("Number of records persisted must be 2", 2, testCollection.count());
    // Testing the save logic
    Document record1 = testCollection.find(eq(MONGO_ID, "testSave1")).first();
    assertEquals("Scientist field of 'testSave1' must equal 'Einstein'", "Einstein", record1.get("scientist"));
    record1.put("scientist", "Darwin");
    result = template.requestBody("direct:save", record1);
    assertTrue(result instanceof UpdateResult);
    record1 = testCollection.find(eq(MONGO_ID, "testSave1")).first();
    assertEquals("Scientist field of 'testSave1' must equal 'Darwin' after save operation", "Darwin", record1.get("scientist"));
}
Also used : List(java.util.List) Arrays.asList(java.util.Arrays.asList) Document(org.bson.Document) UpdateResult(com.mongodb.client.result.UpdateResult) Test(org.junit.Test)

Aggregations

UpdateResult (com.mongodb.client.result.UpdateResult)17 Document (org.bson.Document)10 Test (org.junit.Test)9 Exchange (org.apache.camel.Exchange)5 Processor (org.apache.camel.Processor)5 Formatter (java.util.Formatter)4 Bson (org.bson.conversions.Bson)4 BasicDBObject (com.mongodb.BasicDBObject)3 DBObject (com.mongodb.DBObject)3 List (java.util.List)3 BsonDocument (org.bson.BsonDocument)3 UpdateOptions (com.mongodb.client.model.UpdateOptions)2 DeleteResult (com.mongodb.client.result.DeleteResult)2 ArrayList (java.util.ArrayList)2 Arrays.asList (java.util.Arrays.asList)2 HashMap (java.util.HashMap)2 ImmutableSet (com.google.common.collect.ImmutableSet)1 Block (com.mongodb.Block)1 MongoClient (com.mongodb.MongoClient)1 MongoClientURI (com.mongodb.MongoClientURI)1