Search in sources :

Example 51 with UpdateResult

use of com.mongodb.client.result.UpdateResult in project spring-data-mongodb by spring-projects.

the class MongoTemplate method doUpdate.

protected UpdateResult doUpdate(final String collectionName, final Query query, final Update update, @Nullable final Class<?> entityClass, final boolean upsert, final boolean multi) {
    Assert.notNull(collectionName, "CollectionName must not be null!");
    Assert.notNull(query, "Query must not be null!");
    Assert.notNull(update, "Update must not be null!");
    return execute(collectionName, new CollectionCallback<UpdateResult>() {

        public UpdateResult doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException {
            MongoPersistentEntity<?> entity = entityClass == null ? null : getPersistentEntity(entityClass);
            increaseVersionForUpdateIfNecessary(entity, update);
            UpdateOptions opts = new UpdateOptions();
            opts.upsert(upsert);
            Document queryObj = new Document();
            if (query != null) {
                queryObj.putAll(queryMapper.getMappedObject(query.getQueryObject(), entity));
                query.getCollation().map(Collation::toMongoCollation).ifPresent(opts::collation);
            }
            Document updateObj = update == null ? new Document() : updateMapper.getMappedObject(update.getUpdateObject(), entity);
            if (multi && update.isIsolated() && !queryObj.containsKey("$isolated")) {
                queryObj.put("$isolated", 1);
            }
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Calling update using query: {} and update: {} in collection: {}", serializeToJsonSafely(queryObj), serializeToJsonSafely(updateObj), collectionName);
            }
            MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.UPDATE, collectionName, entityClass, updateObj, queryObj);
            WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
            collection = writeConcernToUse != null ? collection.withWriteConcern(writeConcernToUse) : collection;
            if (!UpdateMapper.isUpdateObject(updateObj)) {
                return collection.replaceOne(queryObj, updateObj, opts);
            } else {
                if (multi) {
                    return collection.updateMany(queryObj, updateObj, opts);
                } else {
                    return collection.updateOne(queryObj, updateObj, opts);
                }
            }
        }
    });
}
Also used : MongoException(com.mongodb.MongoException) MongoPersistentEntity(org.springframework.data.mongodb.core.mapping.MongoPersistentEntity) WriteConcern(com.mongodb.WriteConcern) Document(org.bson.Document) Collation(org.springframework.data.mongodb.core.query.Collation) UpdateResult(com.mongodb.client.result.UpdateResult) DataAccessException(org.springframework.dao.DataAccessException)

Example 52 with UpdateResult

use of com.mongodb.client.result.UpdateResult in project spring-data-mongodb by spring-projects.

the class ReactiveMongoTemplate method doUpdate.

protected Mono<UpdateResult> doUpdate(final String collectionName, @Nullable Query query, @Nullable Update update, @Nullable Class<?> entityClass, final boolean upsert, final boolean multi) {
    MongoPersistentEntity<?> entity = entityClass == null ? null : getPersistentEntity(entityClass);
    Flux<UpdateResult> result = execute(collectionName, collection -> {
        increaseVersionForUpdateIfNecessary(entity, update);
        Document queryObj = query == null ? new Document() : queryMapper.getMappedObject(query.getQueryObject(), entity);
        Document updateObj = update == null ? new Document() : updateMapper.getMappedObject(update.getUpdateObject(), entity);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(String.format("Calling update using query: %s and update: %s in collection: %s", serializeToJsonSafely(queryObj), serializeToJsonSafely(updateObj), collectionName));
        }
        MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.UPDATE, collectionName, entityClass, updateObj, queryObj);
        WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
        MongoCollection<Document> collectionToUse = prepareCollection(collection, writeConcernToUse);
        UpdateOptions updateOptions = new UpdateOptions().upsert(upsert);
        query.getCollation().map(Collation::toMongoCollation).ifPresent(updateOptions::collation);
        if (!UpdateMapper.isUpdateObject(updateObj)) {
            return collectionToUse.replaceOne(queryObj, updateObj, updateOptions);
        }
        if (multi) {
            return collectionToUse.updateMany(queryObj, updateObj, updateOptions);
        }
        return collectionToUse.updateOne(queryObj, updateObj, updateOptions);
    }).doOnNext(updateResult -> {
        if (entity != null && entity.hasVersionProperty() && !multi) {
            if (updateResult.wasAcknowledged() && updateResult.getMatchedCount() == 0) {
                Document queryObj = query == null ? new Document() : queryMapper.getMappedObject(query.getQueryObject(), entity);
                Document updateObj = update == null ? new Document() : updateMapper.getMappedObject(update.getUpdateObject(), entity);
                if (dbObjectContainsVersionProperty(queryObj, entity))
                    throw new OptimisticLockingFailureException("Optimistic lock exception on saving entity: " + updateObj.toString() + " to collection " + collectionName);
            }
        }
    });
    return result.next();
}
Also used : Document(org.bson.Document) PropertyReferenceException(org.springframework.data.mapping.PropertyReferenceException) DeleteOptions(com.mongodb.client.model.DeleteOptions) MongoCollection(com.mongodb.reactivestreams.client.MongoCollection) PersistentPropertyAccessor(org.springframework.data.mapping.PersistentPropertyAccessor) ClientSession(com.mongodb.session.ClientSession) FullDocument(com.mongodb.client.model.changestream.FullDocument) Optionals(org.springframework.data.util.Optionals) UpdateResult(com.mongodb.client.result.UpdateResult) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) UpdateOptions(com.mongodb.client.model.UpdateOptions) AggregationOperationContext(org.springframework.data.mongodb.core.aggregation.AggregationOperationContext) ClassUtils(org.springframework.util.ClassUtils) NonNull(lombok.NonNull) NearQuery(org.springframework.data.mongodb.core.query.NearQuery) Aggregation(org.springframework.data.mongodb.core.aggregation.Aggregation) MongoDbFactory(org.springframework.data.mongodb.MongoDbFactory) FindPublisher(com.mongodb.reactivestreams.client.FindPublisher) PropertyPath(org.springframework.data.mapping.PropertyPath) Id(org.springframework.data.annotation.Id) SpelAwareProxyProjectionFactory(org.springframework.data.projection.SpelAwareProxyProjectionFactory) ApplicationContextAware(org.springframework.context.ApplicationContextAware) AfterDeleteEvent(org.springframework.data.mongodb.core.mapping.event.AfterDeleteEvent) java.util(java.util) Validator(org.springframework.data.mongodb.core.validation.Validator) MappingContext(org.springframework.data.mapping.context.MappingContext) FindOneAndUpdateOptions(com.mongodb.client.model.FindOneAndUpdateOptions) CountOptions(com.mongodb.client.model.CountOptions) MongoClient(com.mongodb.reactivestreams.client.MongoClient) Bson(org.bson.conversions.Bson) Filters(com.mongodb.client.model.Filters) ProjectionInformation(org.springframework.data.projection.ProjectionInformation) MappingException(org.springframework.data.mapping.MappingException) CreateCollectionOptions(com.mongodb.client.model.CreateCollectionOptions) MongoDatabase(com.mongodb.reactivestreams.client.MongoDatabase) ConvertingPropertyAccessor(org.springframework.data.mapping.model.ConvertingPropertyAccessor) Nullable(org.springframework.lang.Nullable) MongoSimpleTypes(org.springframework.data.mongodb.core.mapping.MongoSimpleTypes) Success(com.mongodb.reactivestreams.client.Success) ConversionService(org.springframework.core.convert.ConversionService) BeforeConvertEvent(org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent) PrefixingDelegatingAggregationOperationContext(org.springframework.data.mongodb.core.aggregation.PrefixingDelegatingAggregationOperationContext) AfterConvertEvent(org.springframework.data.mongodb.core.mapping.event.AfterConvertEvent) BeforeSaveEvent(org.springframework.data.mongodb.core.mapping.event.BeforeSaveEvent) ReactiveIndexOperations(org.springframework.data.mongodb.core.index.ReactiveIndexOperations) Publisher(org.reactivestreams.Publisher) ObjectUtils(org.springframework.util.ObjectUtils) TypedAggregation(org.springframework.data.mongodb.core.aggregation.TypedAggregation) Mono(reactor.core.publisher.Mono) BeansException(org.springframework.beans.BeansException) MongoMappingEventPublisher(org.springframework.data.mongodb.core.index.MongoMappingEventPublisher) Criteria(org.springframework.data.mongodb.core.query.Criteria) Flux(reactor.core.publisher.Flux) ObjectId(org.bson.types.ObjectId) MongoMappingEvent(org.springframework.data.mongodb.core.mapping.event.MongoMappingEvent) org.springframework.data.mongodb.core.convert(org.springframework.data.mongodb.core.convert) JSONParseException(com.mongodb.util.JSONParseException) RequiredArgsConstructor(lombok.RequiredArgsConstructor) LoggerFactory(org.slf4j.LoggerFactory) Collation(org.springframework.data.mongodb.core.query.Collation) MongoClientVersion(org.springframework.data.mongodb.util.MongoClientVersion) BeforeDeleteEvent(org.springframework.data.mongodb.core.mapping.event.BeforeDeleteEvent) BsonValue(org.bson.BsonValue) PersistenceExceptionTranslator(org.springframework.dao.support.PersistenceExceptionTranslator) OptimisticLockingFailureException(org.springframework.dao.OptimisticLockingFailureException) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) com.mongodb(com.mongodb) Pair(org.springframework.data.util.Pair) Update(org.springframework.data.mongodb.core.query.Update) MongoPersistentEntityIndexCreator(org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator) SerializationUtils(org.springframework.data.mongodb.core.query.SerializationUtils) ReturnDocument(com.mongodb.client.model.ReturnDocument) ApplicationListener(org.springframework.context.ApplicationListener) Collectors(java.util.stream.Collectors) Entry(java.util.Map.Entry) Codec(org.bson.codecs.Codec) ReactiveMongoDatabaseFactory(org.springframework.data.mongodb.ReactiveMongoDatabaseFactory) TypeBasedAggregationOperationContext(org.springframework.data.mongodb.core.aggregation.TypeBasedAggregationOperationContext) Metric(org.springframework.data.geo.Metric) DataAccessException(org.springframework.dao.DataAccessException) MongoMappingContext(org.springframework.data.mongodb.core.mapping.MongoMappingContext) MongoPersistentProperty(org.springframework.data.mongodb.core.mapping.MongoPersistentProperty) Tuple2(reactor.util.function.Tuple2) InvalidDataAccessApiUsageException(org.springframework.dao.InvalidDataAccessApiUsageException) DistinctPublisher(com.mongodb.reactivestreams.client.DistinctPublisher) Function(java.util.function.Function) Distance(org.springframework.data.geo.Distance) EntityReader(org.springframework.data.convert.EntityReader) AfterLoadEvent(org.springframework.data.mongodb.core.mapping.event.AfterLoadEvent) FindOneAndDeleteOptions(com.mongodb.client.model.FindOneAndDeleteOptions) ChangeStreamPublisher(com.mongodb.reactivestreams.client.ChangeStreamPublisher) MongoPersistentEntity(org.springframework.data.mongodb.core.mapping.MongoPersistentEntity) ValidationOptions(com.mongodb.client.model.ValidationOptions) Nonnull(javax.annotation.Nonnull) ApplicationEventPublisherAware(org.springframework.context.ApplicationEventPublisherAware) Logger(org.slf4j.Logger) AggregationOptions(org.springframework.data.mongodb.core.aggregation.AggregationOptions) IndexOperationsAdapter(org.springframework.data.mongodb.core.index.IndexOperationsAdapter) ApplicationContext(org.springframework.context.ApplicationContext) Query(org.springframework.data.mongodb.core.query.Query) Consumer(java.util.function.Consumer) AfterSaveEvent(org.springframework.data.mongodb.core.mapping.event.AfterSaveEvent) AggregatePublisher(com.mongodb.reactivestreams.client.AggregatePublisher) DeleteResult(com.mongodb.client.result.DeleteResult) GeoResult(org.springframework.data.geo.GeoResult) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) MongoCollection(com.mongodb.reactivestreams.client.MongoCollection) OptimisticLockingFailureException(org.springframework.dao.OptimisticLockingFailureException) Document(org.bson.Document) FullDocument(com.mongodb.client.model.changestream.FullDocument) ReturnDocument(com.mongodb.client.model.ReturnDocument) Collation(org.springframework.data.mongodb.core.query.Collation) UpdateResult(com.mongodb.client.result.UpdateResult) UpdateOptions(com.mongodb.client.model.UpdateOptions) FindOneAndUpdateOptions(com.mongodb.client.model.FindOneAndUpdateOptions)

Example 53 with UpdateResult

use of com.mongodb.client.result.UpdateResult in project spring-data-mongodb by spring-projects.

the class ExecutableUpdateOperationSupportTests method upsert.

// DATAMONGO-1563
@Test
public void upsert() {
    UpdateResult result = template.update(Person.class).matching(query(where("id").is("id-3"))).apply(new Update().set("firstname", "Chewbacca")).upsert();
    assertThat(result.getModifiedCount()).isEqualTo(0L);
    assertThat(result.getUpsertedId()).isEqualTo(new BsonString("id-3"));
}
Also used : BsonString(org.bson.BsonString) Update(org.springframework.data.mongodb.core.query.Update) UpdateResult(com.mongodb.client.result.UpdateResult) Test(org.junit.Test)

Example 54 with UpdateResult

use of com.mongodb.client.result.UpdateResult in project spring-data-mongodb by spring-projects.

the class ExecutableUpdateOperationSupportTests method updateWithDifferentDomainClassAndCollection.

// DATAMONGO-1563
@Test
public void updateWithDifferentDomainClassAndCollection() {
    UpdateResult result = template.update(Jedi.class).inCollection(STAR_WARS).matching(query(where("_id").is(han.getId()))).apply(new Update().set("name", "Han")).all();
    assertThat(result.getModifiedCount()).isEqualTo(1L);
    assertThat(result.getUpsertedId()).isNull();
    assertThat(template.findOne(queryHan(), Person.class)).isNotEqualTo(han).hasFieldOrPropertyWithValue("firstname", "Han");
}
Also used : Update(org.springframework.data.mongodb.core.query.Update) UpdateResult(com.mongodb.client.result.UpdateResult) Test(org.junit.Test)

Example 55 with UpdateResult

use of com.mongodb.client.result.UpdateResult in project spring-data-mongodb by spring-projects.

the class ExecutableUpdateOperationSupportTests method updateAll.

// DATAMONGO-1563
@Test
public void updateAll() {
    UpdateResult result = template.update(Person.class).apply(new Update().set("firstname", "Han")).all();
    assertThat(result.getModifiedCount()).isEqualTo(2L);
    assertThat(result.getUpsertedId()).isNull();
}
Also used : Update(org.springframework.data.mongodb.core.query.Update) UpdateResult(com.mongodb.client.result.UpdateResult) 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