Search in sources :

Example 1 with UpdateResult

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

the class GridFSBucketImpl method rename.

@Override
public void rename(final BsonValue id, final String newFilename, final SingleResultCallback<Void> callback) {
    notNull("id", id);
    notNull("newFilename", newFilename);
    notNull("callback", callback);
    final SingleResultCallback<Void> errHandlingCallback = errorHandlingCallback(callback, LOGGER);
    filesCollection.updateOne(new BsonDocument("_id", id), new BsonDocument("$set", new BsonDocument("filename", new BsonString(newFilename))), new SingleResultCallback<UpdateResult>() {

        @Override
        public void onResult(final UpdateResult result, final Throwable t) {
            if (t != null) {
                errHandlingCallback.onResult(null, t);
            } else if (result.wasAcknowledged() && result.getMatchedCount() == 0) {
                errHandlingCallback.onResult(null, new MongoGridFSException(format("No file found with the ObjectId: %s", id)));
            } else {
                errHandlingCallback.onResult(null, null);
            }
        }
    });
}
Also used : BsonDocument(org.bson.BsonDocument) BsonString(org.bson.BsonString) MongoGridFSException(com.mongodb.MongoGridFSException) UpdateResult(com.mongodb.client.result.UpdateResult)

Example 2 with UpdateResult

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

the class GridFSTest method arrangeGridFS.

private void arrangeGridFS(final BsonDocument arrange) {
    if (arrange.isEmpty()) {
        return;
    }
    for (BsonValue fileToArrange : arrange.getArray("data", new BsonArray())) {
        final BsonDocument document = fileToArrange.asDocument();
        if (document.containsKey("delete") && document.containsKey("deletes")) {
            for (BsonValue toDelete : document.getArray("deletes")) {
                final BsonDocument query = toDelete.asDocument().getDocument("q");
                int limit = toDelete.asDocument().getInt32("limit").getValue();
                final MongoCollection<BsonDocument> collection;
                if (document.getString("delete").getValue().equals("fs.files")) {
                    collection = filesCollection;
                } else {
                    collection = chunksCollection;
                }
                if (limit == 1) {
                    new MongoOperation<DeleteResult>() {

                        @Override
                        public void execute() {
                            collection.deleteOne(query, getCallback());
                        }
                    }.get();
                } else {
                    new MongoOperation<DeleteResult>() {

                        @Override
                        public void execute() {
                            collection.deleteMany(query, getCallback());
                        }
                    }.get();
                }
            }
        } else if (document.containsKey("insert") && document.containsKey("documents")) {
            if (document.getString("insert").getValue().equals("fs.files")) {
                new MongoOperation<Void>() {

                    @Override
                    public void execute() {
                        filesCollection.insertMany(processFiles(document.getArray("documents"), new ArrayList<BsonDocument>()), getCallback());
                    }
                }.get();
            } else {
                new MongoOperation<Void>() {

                    @Override
                    public void execute() {
                        chunksCollection.insertMany(processChunks(document.getArray("documents"), new ArrayList<BsonDocument>()), getCallback());
                    }
                }.get();
            }
        } else if (document.containsKey("update") && document.containsKey("updates")) {
            final MongoCollection<BsonDocument> collection;
            if (document.getString("update").getValue().equals("fs.files")) {
                collection = filesCollection;
            } else {
                collection = chunksCollection;
            }
            for (BsonValue rawUpdate : document.getArray("updates")) {
                final BsonDocument query = rawUpdate.asDocument().getDocument("q");
                final BsonDocument update = rawUpdate.asDocument().getDocument("u");
                update.put("$set", parseHexDocument(update.getDocument("$set")));
                new MongoOperation<UpdateResult>() {

                    @Override
                    public void execute() {
                        collection.updateMany(query, update, getCallback());
                    }
                }.get();
            }
        } else {
            throw new IllegalArgumentException("Unsupported arrange: " + document);
        }
    }
}
Also used : ArrayList(java.util.ArrayList) BsonDocument(org.bson.BsonDocument) BsonArray(org.bson.BsonArray) DeleteResult(com.mongodb.client.result.DeleteResult) UpdateResult(com.mongodb.client.result.UpdateResult) BsonValue(org.bson.BsonValue)

Example 3 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 4 with UpdateResult

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

the class MongoDbOperationsTest method testUpdate.

@Test
public void testUpdate() throws Exception {
    // Prepare test
    assertEquals(0, testCollection.count());
    for (int i = 1; i <= 100; i++) {
        String body = null;
        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
    BasicDBObject extraField = new BasicDBObject("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 BasicDBObject("scientist", "Darwin")));
    DBObject updateObj = new BasicDBObject("$set", new BasicDBObject("scientist", "Darwin"));
    Exchange resultExchange = template.request("direct:update", new Processor() {

        @Override
        public void process(Exchange exchange) throws Exception {
            exchange.getIn().setBody(new Object[] { extraField, updateObj });
            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 BasicDBObject("scientist", "Darwin")));
}
Also used : Exchange(org.apache.camel.Exchange) BasicDBObject(com.mongodb.BasicDBObject) Processor(org.apache.camel.Processor) Formatter(java.util.Formatter) BasicDBObject(com.mongodb.BasicDBObject) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) DBObject(com.mongodb.DBObject) UpdateResult(com.mongodb.client.result.UpdateResult) Test(org.junit.Test)

Example 5 with UpdateResult

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

the class MongoDbOperationsTest method testUpdate.

@Test
public void testUpdate() 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"));
    Exchange resultExchange = template.request("direct:update", new Processor() {

        @Override
        public void process(Exchange exchange) throws Exception {
            exchange.getIn().setBody(new Bson[] { extraField, updateObj });
            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)

Aggregations

UpdateResult (com.mongodb.client.result.UpdateResult)74 Document (org.bson.Document)31 Test (org.junit.Test)20 Bson (org.bson.conversions.Bson)16 Update (org.springframework.data.mongodb.core.query.Update)12 Test (org.testng.annotations.Test)11 UpdateOptions (com.mongodb.client.model.UpdateOptions)10 BasicDBObject (com.mongodb.BasicDBObject)9 FindOptions (dev.morphia.query.FindOptions)8 BsonDocument (org.bson.BsonDocument)8 FindOneAndUpdateOptions (com.mongodb.client.model.FindOneAndUpdateOptions)7 DeleteResult (com.mongodb.client.result.DeleteResult)7 Query (org.springframework.data.mongodb.core.query.Query)7 ObjectId (org.bson.types.ObjectId)6 UpdateOptions (dev.morphia.UpdateOptions)5 ArrayList (java.util.ArrayList)5 Exchange (org.apache.camel.Exchange)5 Processor (org.apache.camel.Processor)5 DBObject (com.mongodb.DBObject)4 Formatter (java.util.Formatter)4