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));
}
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));
}
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));
}
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);
}
}
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);
}
}
Aggregations