Search in sources :

Example 1 with FindOneAndUpdateOptions

use of com.mongodb.client.model.FindOneAndUpdateOptions in project mongo-java-driver by mongodb.

the class FindAndUpdateAcceptanceTest method shouldFindAndReplaceWithDocumentRequiringACustomEncoder.

@Test
public void shouldFindAndReplaceWithDocumentRequiringACustomEncoder() {
    Worker pat = new Worker(new ObjectId(), "Pat", "Sales", new Date(), 7);
    CodecRegistry codecRegistry = fromProviders(asList(new ValueCodecProvider(), new DocumentCodecProvider(), new BsonValueCodecProvider(), new WorkerCodecProvider()));
    MongoCollection<Worker> collection = database.getCollection(getCollectionName(), Worker.class).withCodecRegistry(codecRegistry);
    collection.insertOne(pat);
    assertThat(collection.count(), is(1L));
    Document updateOperation = new Document("$inc", new Document("numberOfJobs", 1));
    Worker updatedDocument = collection.findOneAndUpdate(new Document("name", "Pat"), updateOperation, new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER));
    assertThat("Worker returned from updateOneAndGet should have the", updatedDocument.getNumberOfJobs(), equalTo(8));
}
Also used : ValueCodecProvider(org.bson.codecs.ValueCodecProvider) BsonValueCodecProvider(org.bson.codecs.BsonValueCodecProvider) ObjectId(org.bson.types.ObjectId) DocumentCodecProvider(org.bson.codecs.DocumentCodecProvider) WorkerCodecProvider(com.mongodb.client.test.WorkerCodecProvider) Worker(com.mongodb.client.test.Worker) FindOneAndUpdateOptions(com.mongodb.client.model.FindOneAndUpdateOptions) Document(org.bson.Document) ReturnDocument(com.mongodb.client.model.ReturnDocument) CodecRegistry(org.bson.codecs.configuration.CodecRegistry) Date(java.util.Date) BsonValueCodecProvider(org.bson.codecs.BsonValueCodecProvider) Test(org.junit.Test)

Example 2 with FindOneAndUpdateOptions

use of com.mongodb.client.model.FindOneAndUpdateOptions in project mongo-java-driver by mongodb.

the class FindAndUpdateAcceptanceTest method shouldUpdateDocumentAndReturnNew.

@Test
public void shouldUpdateDocumentAndReturnNew() {
    Document documentInserted = new Document(KEY, VALUE_TO_CARE_ABOUT).append("someNumber", 11);
    collection.insertOne(documentInserted);
    assertThat(collection.count(), is(1L));
    Document updateOperation = new Document("$inc", new Document("someNumber", 1));
    Document updatedDocument = collection.findOneAndUpdate(new Document(KEY, VALUE_TO_CARE_ABOUT), updateOperation, new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER));
    assertThat("Document returned from updateOneAndGet should be the updated document", (Integer) updatedDocument.get("someNumber"), equalTo(12));
}
Also used : FindOneAndUpdateOptions(com.mongodb.client.model.FindOneAndUpdateOptions) Document(org.bson.Document) ReturnDocument(com.mongodb.client.model.ReturnDocument) Test(org.junit.Test)

Example 3 with FindOneAndUpdateOptions

use of com.mongodb.client.model.FindOneAndUpdateOptions in project mongo-java-driver by mongodb.

the class FindAndUpdateAcceptanceTest method shouldInsertDocumentWhenFilterDoesNotMatchAnyDocumentsAndUpsertSelected.

@Test
public void shouldInsertDocumentWhenFilterDoesNotMatchAnyDocumentsAndUpsertSelected() {
    Document originalDocument = new Document(KEY, VALUE_TO_CARE_ABOUT).append("someNumber", 11);
    collection.insertOne(originalDocument);
    assertThat(collection.count(), is(1L));
    String newValueThatDoesNotMatchAnythingInDatabase = "valueThatDoesNotMatch";
    Document updateOperation = new Document("$inc", new Document("someNumber", 1));
    Document document = collection.findOneAndUpdate(new Document(KEY, newValueThatDoesNotMatchAnythingInDatabase), updateOperation, new FindOneAndUpdateOptions().upsert(true).returnDocument(ReturnDocument.AFTER));
    assertThat(collection.count(), is(2L));
    assertThat("Document retrieved from updateOneAndGet and upsert true should have the new values", (Integer) document.get("someNumber"), equalTo(1));
    assertThat("Document retrieved from updateOneAndGet and upsert true should have the new values", document.get(KEY).toString(), equalTo(newValueThatDoesNotMatchAnythingInDatabase));
}
Also used : FindOneAndUpdateOptions(com.mongodb.client.model.FindOneAndUpdateOptions) Document(org.bson.Document) ReturnDocument(com.mongodb.client.model.ReturnDocument) Test(org.junit.Test)

Example 4 with FindOneAndUpdateOptions

use of com.mongodb.client.model.FindOneAndUpdateOptions in project jackrabbit-oak by apache.

the class MongoDocumentStore method findAndModify.

@SuppressWarnings("unchecked")
@CheckForNull
private <T extends Document> T findAndModify(Collection<T> collection, UpdateOp updateOp, boolean upsert, boolean checkConditions) {
    MongoCollection<BasicDBObject> dbCollection = getDBCollection(collection);
    // make sure we don't modify the original updateOp
    updateOp = updateOp.copy();
    Bson update = createUpdate(updateOp, false);
    Lock lock = null;
    if (collection == Collection.NODES) {
        lock = nodeLocks.acquire(updateOp.getId());
    }
    final Stopwatch watch = startWatch();
    boolean newEntry = false;
    try {
        // get modCount of cached document
        Long modCount = null;
        T cachedDoc = null;
        if (collection == Collection.NODES) {
            cachedDoc = (T) nodesCache.getIfPresent(updateOp.getId());
            if (cachedDoc != null) {
                modCount = cachedDoc.getModCount();
            }
        }
        // if we have a matching modCount
        if (modCount != null) {
            // unnecessary call when the conditions do not match
            if (!checkConditions || UpdateUtils.checkConditions(cachedDoc, updateOp.getConditions())) {
                Bson query = createQueryForUpdate(updateOp.getId(), updateOp.getConditions());
                // below condition may overwrite a user supplied condition
                // on _modCount. This is fine, because the conditions were
                // already checked against the cached document with the
                // matching _modCount value. There is no need to check the
                // user supplied condition on _modCount again on the server
                query = Filters.and(query, Filters.eq(Document.MOD_COUNT, modCount));
                UpdateResult result = dbCollection.updateOne(query, update);
                if (result.getModifiedCount() > 0) {
                    // success, update cached document
                    if (collection == Collection.NODES) {
                        NodeDocument newDoc = (NodeDocument) applyChanges(collection, cachedDoc, updateOp);
                        nodesCache.put(newDoc);
                    }
                    // return previously cached document
                    return cachedDoc;
                }
            }
        }
        // conditional update failed or not possible
        // perform operation and get complete document
        Bson query = createQueryForUpdate(updateOp.getId(), updateOp.getConditions());
        FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.BEFORE).upsert(upsert);
        BasicDBObject oldNode = dbCollection.findOneAndUpdate(query, update, options);
        if (oldNode == null) {
            newEntry = true;
        }
        if (checkConditions && oldNode == null) {
            return null;
        }
        T oldDoc = convertFromDBObject(collection, oldNode);
        if (oldDoc != null) {
            if (collection == Collection.NODES) {
                NodeDocument newDoc = (NodeDocument) applyChanges(collection, oldDoc, updateOp);
                nodesCache.put(newDoc);
                updateLocalChanges(newDoc);
            }
            oldDoc.seal();
        } else if (upsert) {
            if (collection == Collection.NODES) {
                NodeDocument doc = (NodeDocument) collection.newDocument(this);
                UpdateUtils.applyChanges(doc, updateOp);
                nodesCache.putIfAbsent(doc);
                updateLocalChanges(doc);
            }
        } else {
        // updateOp without conditions and not an upsert
        // this means the document does not exist
        }
        return oldDoc;
    } catch (Exception e) {
        throw handleException(e, collection, updateOp.getId());
    } finally {
        if (lock != null) {
            lock.unlock();
        }
        stats.doneFindAndModify(watch.elapsed(TimeUnit.NANOSECONDS), collection, updateOp.getId(), newEntry, true, 0);
    }
}
Also used : BasicDBObject(com.mongodb.BasicDBObject) Stopwatch(com.google.common.base.Stopwatch) FindOneAndUpdateOptions(com.mongodb.client.model.FindOneAndUpdateOptions) NodeDocument(org.apache.jackrabbit.oak.plugins.document.NodeDocument) UpdateResult(com.mongodb.client.result.UpdateResult) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) MongoBulkWriteException(com.mongodb.MongoBulkWriteException) MongoException(com.mongodb.MongoException) DocumentStoreException.asDocumentStoreException(org.apache.jackrabbit.oak.plugins.document.DocumentStoreException.asDocumentStoreException) DocumentStoreException(org.apache.jackrabbit.oak.plugins.document.DocumentStoreException) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) Bson(org.bson.conversions.Bson) Lock(java.util.concurrent.locks.Lock) CheckForNull(javax.annotation.CheckForNull)

Example 5 with FindOneAndUpdateOptions

use of com.mongodb.client.model.FindOneAndUpdateOptions in project engine by Lumeer.

the class MongoDbStorage method resetSequence.

@Override
public synchronized void resetSequence(final String collectionName, final String indexAttribute, final String index) {
    final FindOneAndUpdateOptions options = new FindOneAndUpdateOptions();
    options.returnDocument(ReturnDocument.AFTER);
    final Document doc = database.getCollection(collectionName).findOneAndUpdate(eq(indexAttribute, index), set("seq", 0), options);
    if (doc == null) {
        Document newSeq = new Document();
        newSeq.put(indexAttribute, index);
        newSeq.put("seq", 0);
        database.getCollection(collectionName).insertOne(newSeq);
    }
}
Also used : FindOneAndUpdateOptions(com.mongodb.client.model.FindOneAndUpdateOptions) Document(org.bson.Document) DataDocument(io.lumeer.engine.api.data.DataDocument) ReturnDocument(com.mongodb.client.model.ReturnDocument) BsonDocument(org.bson.BsonDocument)

Aggregations

FindOneAndUpdateOptions (com.mongodb.client.model.FindOneAndUpdateOptions)16 Document (org.bson.Document)9 Bson (org.bson.conversions.Bson)7 ReturnDocument (com.mongodb.client.model.ReturnDocument)6 Test (org.junit.jupiter.api.Test)6 BsonDocument (org.bson.BsonDocument)5 BasicQuery (org.springframework.data.mongodb.core.query.BasicQuery)5 Update (org.springframework.data.mongodb.core.query.Update)5 DataDocument (io.lumeer.engine.api.data.DataDocument)3 Test (org.junit.Test)3 ArrayList (java.util.ArrayList)2 List (java.util.List)2 AggregationUpdate (org.springframework.data.mongodb.core.aggregation.AggregationUpdate)2 Stopwatch (com.google.common.base.Stopwatch)1 UncheckedExecutionException (com.google.common.util.concurrent.UncheckedExecutionException)1 BasicDBObject (com.mongodb.BasicDBObject)1 MongoBulkWriteException (com.mongodb.MongoBulkWriteException)1 MongoException (com.mongodb.MongoException)1 ClientSession (com.mongodb.client.ClientSession)1 UpdateResult (com.mongodb.client.result.UpdateResult)1