Search in sources :

Example 16 with WriteConcern

use of com.mongodb.WriteConcern in project spring-data-mongodb by spring-projects.

the class MongoTemplate method doUpdate.

@SuppressWarnings("ConstantConditions")
protected UpdateResult doUpdate(String collectionName, Query query, UpdateDefinition update, @Nullable Class<?> entityClass, boolean upsert, 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!");
    if (query.isSorted() && LOGGER.isWarnEnabled()) {
        LOGGER.warn(String.format("%s does not support sort ('%s'). Please use findAndModify() instead.", upsert ? "Upsert" : "UpdateFirst", serializeToJsonSafely(query.getSortObject())));
    }
    MongoPersistentEntity<?> entity = entityClass == null ? null : getPersistentEntity(entityClass);
    UpdateContext updateContext = multi ? queryOperations.updateContext(update, query, upsert) : queryOperations.updateSingleContext(update, query, upsert);
    updateContext.increaseVersionForUpdateIfNecessary(entity);
    Document queryObj = updateContext.getMappedQuery(entity);
    UpdateOptions opts = updateContext.getUpdateOptions(entityClass);
    if (updateContext.isAggregationUpdate()) {
        List<Document> pipeline = updateContext.getUpdatePipeline(entityClass);
        MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.UPDATE, collectionName, entityClass, update.getUpdateObject(), queryObj);
        WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
        return execute(collectionName, collection -> {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(String.format("Calling update using query: %s and update: %s in collection: %s", serializeToJsonSafely(queryObj), serializeToJsonSafely(pipeline), collectionName));
            }
            collection = writeConcernToUse != null ? collection.withWriteConcern(writeConcernToUse) : collection;
            return multi ? collection.updateMany(queryObj, pipeline, opts) : collection.updateOne(queryObj, pipeline, opts);
        });
    }
    Document updateObj = updateContext.getMappedUpdate(entity);
    MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.UPDATE, collectionName, entityClass, updateObj, queryObj);
    WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
    return execute(collectionName, collection -> {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(String.format("Calling update using query: %s and update: %s in collection: %s", serializeToJsonSafely(queryObj), serializeToJsonSafely(updateObj), collectionName));
        }
        collection = writeConcernToUse != null ? collection.withWriteConcern(writeConcernToUse) : collection;
        if (!UpdateMapper.isUpdateObject(updateObj)) {
            Document filter = new Document(queryObj);
            if (updateContext.requiresShardKey(filter, entity)) {
                if (entity.getShardKey().isImmutable()) {
                    filter = updateContext.applyShardKey(entity, filter, null);
                } else {
                    filter = updateContext.applyShardKey(entity, filter, collection.find(filter, Document.class).projection(updateContext.getMappedShardKey(entity)).first());
                }
            }
            ReplaceOptions replaceOptions = updateContext.getReplaceOptions(entityClass);
            return collection.replaceOne(filter, updateObj, replaceOptions);
        } else {
            return multi ? collection.updateMany(queryObj, updateObj, opts) : collection.updateOne(queryObj, updateObj, opts);
        }
    });
}
Also used : WriteConcern(com.mongodb.WriteConcern) UpdateContext(org.springframework.data.mongodb.core.QueryOperations.UpdateContext) Document(org.bson.Document)

Example 17 with WriteConcern

use of com.mongodb.WriteConcern in project spring-data-mongodb by spring-projects.

the class MongoTemplate method insertDocument.

@SuppressWarnings("ConstantConditions")
protected Object insertDocument(String collectionName, Document document, Class<?> entityClass) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(String.format("Inserting Document containing fields: %s in collection: %s", document.keySet(), collectionName));
    }
    return execute(collectionName, collection -> {
        MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.INSERT, collectionName, entityClass, document, null);
        WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
        if (writeConcernToUse == null) {
            collection.insertOne(document);
        } else {
            collection.withWriteConcern(writeConcernToUse).insertOne(document);
        }
        return operations.forEntity(document).getId();
    });
}
Also used : WriteConcern(com.mongodb.WriteConcern)

Example 18 with WriteConcern

use of com.mongodb.WriteConcern in project spring-data-mongodb by spring-projects.

the class MongoTemplate method doRemove.

@SuppressWarnings("ConstantConditions")
protected <T> DeleteResult doRemove(String collectionName, Query query, @Nullable Class<T> entityClass, boolean multi) {
    Assert.notNull(query, "Query must not be null!");
    Assert.hasText(collectionName, "Collection name must not be null or empty!");
    MongoPersistentEntity<?> entity = getPersistentEntity(entityClass);
    DeleteContext deleteContext = multi ? queryOperations.deleteQueryContext(query) : queryOperations.deleteSingleContext(query);
    Document queryObject = deleteContext.getMappedQuery(entity);
    DeleteOptions options = deleteContext.getDeleteOptions(entityClass);
    MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.REMOVE, collectionName, entityClass, null, queryObject);
    WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
    return execute(collectionName, collection -> {
        maybeEmitEvent(new BeforeDeleteEvent<>(queryObject, entityClass, collectionName));
        Document removeQuery = queryObject;
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(String.format("Remove using query: %s in collection: %s.", serializeToJsonSafely(removeQuery), collectionName));
        }
        if (query.getLimit() > 0 || query.getSkip() > 0) {
            MongoCursor<Document> cursor = new QueryCursorPreparer(query, entityClass).prepare(// 
            collection.find(removeQuery).projection(MappedDocument.getIdOnlyProjection())).iterator();
            Set<Object> ids = new LinkedHashSet<>();
            while (cursor.hasNext()) {
                ids.add(MappedDocument.of(cursor.next()).getId());
            }
            removeQuery = MappedDocument.getIdIn(ids);
        }
        MongoCollection<Document> collectionToUse = writeConcernToUse != null ? collection.withWriteConcern(writeConcernToUse) : collection;
        DeleteResult result = multi ? collectionToUse.deleteMany(removeQuery, options) : collectionToUse.deleteOne(removeQuery, options);
        maybeEmitEvent(new AfterDeleteEvent<>(queryObject, entityClass, collectionName));
        return result;
    });
}
Also used : DeleteContext(org.springframework.data.mongodb.core.QueryOperations.DeleteContext) Document(org.bson.Document) WriteConcern(com.mongodb.WriteConcern) DeleteResult(com.mongodb.client.result.DeleteResult)

Example 19 with WriteConcern

use of com.mongodb.WriteConcern in project spring-data-mongodb by spring-projects.

the class ReactiveMongoTemplate method doUpdate.

protected Mono<UpdateResult> doUpdate(String collectionName, Query query, @Nullable UpdateDefinition update, @Nullable Class<?> entityClass, boolean upsert, boolean multi) {
    if (query.isSorted() && LOGGER.isWarnEnabled()) {
        LOGGER.warn(String.format("%s does not support sort ('%s'). Please use findAndModify() instead.", upsert ? "Upsert" : "UpdateFirst", serializeToJsonSafely(query.getSortObject())));
    }
    MongoPersistentEntity<?> entity = entityClass == null ? null : getPersistentEntity(entityClass);
    UpdateContext updateContext = multi ? queryOperations.updateContext(update, query, upsert) : queryOperations.updateSingleContext(update, query, upsert);
    updateContext.increaseVersionForUpdateIfNecessary(entity);
    Document queryObj = updateContext.getMappedQuery(entity);
    UpdateOptions updateOptions = updateContext.getUpdateOptions(entityClass);
    Flux<UpdateResult> result;
    if (updateContext.isAggregationUpdate()) {
        List<Document> pipeline = updateContext.getUpdatePipeline(entityClass);
        MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.UPDATE, collectionName, entityClass, update.getUpdateObject(), queryObj);
        WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
        result = execute(collectionName, collection -> {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(String.format("Calling update using query: %s and update: %s in collection: %s", serializeToJsonSafely(queryObj), serializeToJsonSafely(pipeline), collectionName));
            }
            collection = writeConcernToUse != null ? collection.withWriteConcern(writeConcernToUse) : collection;
            return multi ? collection.updateMany(queryObj, pipeline, updateOptions) : collection.updateOne(queryObj, pipeline, updateOptions);
        });
    } else {
        Document updateObj = updateContext.getMappedUpdate(entity);
        MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.UPDATE, collectionName, entityClass, updateObj, queryObj);
        WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
        result = execute(collectionName, collection -> {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(String.format("Calling update using query: %s and update: %s in collection: %s", serializeToJsonSafely(queryObj), serializeToJsonSafely(updateObj), collectionName));
            }
            MongoCollection<Document> collectionToUse = prepareCollection(collection, writeConcernToUse);
            if (!UpdateMapper.isUpdateObject(updateObj)) {
                Document filter = new Document(queryObj);
                Mono<Document> deferredFilter;
                if (updateContext.requiresShardKey(filter, entity)) {
                    if (entity.getShardKey().isImmutable()) {
                        deferredFilter = Mono.just(updateContext.applyShardKey(entity, filter, null));
                    } else {
                        deferredFilter = Mono.from(collection.find(filter, Document.class).projection(updateContext.getMappedShardKey(entity)).first()).defaultIfEmpty(updateObj).map(it -> updateContext.applyShardKey(entity, filter, it));
                    }
                } else {
                    deferredFilter = Mono.just(filter);
                }
                ReplaceOptions replaceOptions = updateContext.getReplaceOptions(entityClass);
                return deferredFilter.flatMap(it -> Mono.from(collectionToUse.replaceOne(it, updateObj, replaceOptions)));
            }
            return multi ? collectionToUse.updateMany(queryObj, updateObj, updateOptions) : collectionToUse.updateOne(queryObj, updateObj, updateOptions);
        });
    }
    result = result.doOnNext(updateResult -> {
        if (entity != null && entity.hasVersionProperty() && !multi) {
            if (updateResult.wasAcknowledged() && updateResult.getMatchedCount() == 0) {
                Document updateObj = updateContext.getMappedUpdate(entity);
                if (containsVersionProperty(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) Arrays(java.util.Arrays) BasicQuery(org.springframework.data.mongodb.core.query.BasicQuery) NumberUtils(org.springframework.util.NumberUtils) BsonUtils(org.springframework.data.mongodb.util.BsonUtils) Tuples(reactor.util.function.Tuples) MongoCollection(com.mongodb.reactivestreams.client.MongoCollection) ReactiveMongoDatabaseUtils(org.springframework.data.mongodb.ReactiveMongoDatabaseUtils) FullDocument(com.mongodb.client.model.changestream.FullDocument) QueryContext(org.springframework.data.mongodb.core.QueryOperations.QueryContext) Optionals(org.springframework.data.util.Optionals) UpdateResult(com.mongodb.client.result.UpdateResult) Map(java.util.Map) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) CursorOption(org.springframework.data.mongodb.core.query.Meta.CursorOption) MongoJsonSchemaMapper(org.springframework.data.mongodb.core.convert.MongoJsonSchemaMapper) AggregationOperationContext(org.springframework.data.mongodb.core.aggregation.AggregationOperationContext) ClassUtils(org.springframework.util.ClassUtils) NearQuery(org.springframework.data.mongodb.core.query.NearQuery) MappingContextEvent(org.springframework.data.mapping.context.MappingContextEvent) Aggregation(org.springframework.data.mongodb.core.aggregation.Aggregation) CollectionUtils(org.springframework.util.CollectionUtils) FindPublisher(com.mongodb.reactivestreams.client.FindPublisher) LogFactory(org.apache.commons.logging.LogFactory) DistinctQueryContext(org.springframework.data.mongodb.core.QueryOperations.DistinctQueryContext) ApplicationContextAware(org.springframework.context.ApplicationContextAware) Validator(org.springframework.data.mongodb.core.validation.Validator) MongoCustomConversions(org.springframework.data.mongodb.core.convert.MongoCustomConversions) MappingContext(org.springframework.data.mapping.context.MappingContext) ArrayList(java.util.ArrayList) UpdateDefinition(org.springframework.data.mongodb.core.query.UpdateDefinition) MongoClient(com.mongodb.reactivestreams.client.MongoClient) Bson(org.bson.conversions.Bson) NoOpDbRefResolver(org.springframework.data.mongodb.core.convert.NoOpDbRefResolver) ReactiveMongoPersistentEntityIndexCreator(org.springframework.data.mongodb.core.index.ReactiveMongoPersistentEntityIndexCreator) DbRefResolver(org.springframework.data.mongodb.core.convert.DbRefResolver) MappingException(org.springframework.data.mapping.MappingException) MongoDatabase(com.mongodb.reactivestreams.client.MongoDatabase) Nullable(org.springframework.lang.Nullable) JsonSchemaMapper(org.springframework.data.mongodb.core.convert.JsonSchemaMapper) MongoSimpleTypes(org.springframework.data.mongodb.core.mapping.MongoSimpleTypes) com.mongodb.client.model(com.mongodb.client.model) PrefixingDelegatingAggregationOperationContext(org.springframework.data.mongodb.core.aggregation.PrefixingDelegatingAggregationOperationContext) CountContext(org.springframework.data.mongodb.core.QueryOperations.CountContext) ReactiveIndexOperations(org.springframework.data.mongodb.core.index.ReactiveIndexOperations) org.springframework.data.mongodb.core.mapping.event(org.springframework.data.mongodb.core.mapping.event) QueryMapper(org.springframework.data.mongodb.core.convert.QueryMapper) Publisher(org.reactivestreams.Publisher) ObjectUtils(org.springframework.util.ObjectUtils) DeleteContext(org.springframework.data.mongodb.core.QueryOperations.DeleteContext) 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) RelaxedTypeBasedAggregationOperationContext(org.springframework.data.mongodb.core.aggregation.RelaxedTypeBasedAggregationOperationContext) ResourceUtils(org.springframework.util.ResourceUtils) Flux(reactor.core.publisher.Flux) ObjectId(org.bson.types.ObjectId) Collation(org.springframework.data.mongodb.core.query.Collation) EntityProjection(org.springframework.data.projection.EntityProjection) BsonValue(org.bson.BsonValue) PersistenceExceptionTranslator(org.springframework.dao.support.PersistenceExceptionTranslator) OptimisticLockingFailureException(org.springframework.dao.OptimisticLockingFailureException) MapReduceOptions(org.springframework.data.mongodb.core.mapreduce.MapReduceOptions) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) AdaptibleEntity(org.springframework.data.mongodb.core.EntityOperations.AdaptibleEntity) CursorType(com.mongodb.CursorType) MongoWriter(org.springframework.data.mongodb.core.convert.MongoWriter) Meta(org.springframework.data.mongodb.core.query.Meta) ReactiveEntityCallbacks(org.springframework.data.mapping.callback.ReactiveEntityCallbacks) InsertOneResult(com.mongodb.client.result.InsertOneResult) SerializationUtils(org.springframework.data.mongodb.core.query.SerializationUtils) MongoException(com.mongodb.MongoException) Collection(java.util.Collection) ApplicationListener(org.springframework.context.ApplicationListener) Collectors(java.util.stream.Collectors) PersistentEntity(org.springframework.data.mapping.PersistentEntity) List(java.util.List) Optional(java.util.Optional) UpdateMapper(org.springframework.data.mongodb.core.convert.UpdateMapper) ReactiveMongoDatabaseFactory(org.springframework.data.mongodb.ReactiveMongoDatabaseFactory) TypeBasedAggregationOperationContext(org.springframework.data.mongodb.core.aggregation.TypeBasedAggregationOperationContext) UpdateContext(org.springframework.data.mongodb.core.QueryOperations.UpdateContext) Metric(org.springframework.data.geo.Metric) ReadPreference(com.mongodb.ReadPreference) 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) HashMap(java.util.HashMap) InvalidDataAccessApiUsageException(org.springframework.dao.InvalidDataAccessApiUsageException) DistinctPublisher(com.mongodb.reactivestreams.client.DistinctPublisher) MongoDatabaseFactory(org.springframework.data.mongodb.MongoDatabaseFactory) MongoConverter(org.springframework.data.mongodb.core.convert.MongoConverter) Function(java.util.function.Function) Distance(org.springframework.data.geo.Distance) EntityReader(org.springframework.data.convert.EntityReader) ChangeStreamPublisher(com.mongodb.reactivestreams.client.ChangeStreamPublisher) ArrayFilter(org.springframework.data.mongodb.core.query.UpdateDefinition.ArrayFilter) Granularity(org.springframework.data.mongodb.core.timeseries.Granularity) MongoPersistentEntity(org.springframework.data.mongodb.core.mapping.MongoPersistentEntity) AggregationDefinition(org.springframework.data.mongodb.core.QueryOperations.AggregationDefinition) Subscriber(org.reactivestreams.Subscriber) ApplicationEventPublisherAware(org.springframework.context.ApplicationEventPublisherAware) Iterator(java.util.Iterator) AggregationOptions(org.springframework.data.mongodb.core.aggregation.AggregationOptions) MapReducePublisher(com.mongodb.reactivestreams.client.MapReducePublisher) ClientSession(com.mongodb.reactivestreams.client.ClientSession) ApplicationContext(org.springframework.context.ApplicationContext) Query(org.springframework.data.mongodb.core.query.Query) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) MappingMongoConverter(org.springframework.data.mongodb.core.convert.MappingMongoConverter) AggregatePublisher(com.mongodb.reactivestreams.client.AggregatePublisher) ClientSessionOptions(com.mongodb.ClientSessionOptions) DeleteResult(com.mongodb.client.result.DeleteResult) Log(org.apache.commons.logging.Log) GeoResult(org.springframework.data.geo.GeoResult) SessionSynchronization(org.springframework.data.mongodb.SessionSynchronization) WriteConcern(com.mongodb.WriteConcern) Collections(java.util.Collections) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) Mono(reactor.core.publisher.Mono) UpdateContext(org.springframework.data.mongodb.core.QueryOperations.UpdateContext) Document(org.bson.Document) FullDocument(com.mongodb.client.model.changestream.FullDocument) MongoCollection(com.mongodb.reactivestreams.client.MongoCollection) OptimisticLockingFailureException(org.springframework.dao.OptimisticLockingFailureException) WriteConcern(com.mongodb.WriteConcern) UpdateResult(com.mongodb.client.result.UpdateResult)

Example 20 with WriteConcern

use of com.mongodb.WriteConcern in project spring-data-mongodb by spring-projects.

the class ReactiveMongoTemplate method insertDocument.

protected Mono<Object> insertDocument(String collectionName, Document dbDoc, Class<?> entityClass) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(String.format("Inserting Document containing fields: " + dbDoc.keySet() + " in collection: " + collectionName));
    }
    Document document = new Document(dbDoc);
    Flux<InsertOneResult> execute = execute(collectionName, collection -> {
        MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.INSERT, collectionName, entityClass, dbDoc, null);
        WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
        MongoCollection<Document> collectionToUse = prepareCollection(collection, writeConcernToUse);
        return collectionToUse.insertOne(document);
    });
    return Flux.from(execute).last().map(success -> MappedDocument.of(document).getId());
}
Also used : WriteConcern(com.mongodb.WriteConcern) Document(org.bson.Document) FullDocument(com.mongodb.client.model.changestream.FullDocument) InsertOneResult(com.mongodb.client.result.InsertOneResult)

Aggregations

WriteConcern (com.mongodb.WriteConcern)53 Document (org.bson.Document)14 MongoException (com.mongodb.MongoException)11 List (java.util.List)11 ArrayList (java.util.ArrayList)9 ReadPreference (com.mongodb.ReadPreference)8 Map (java.util.Map)8 Collectors (java.util.stream.Collectors)8 TimeUnit (java.util.concurrent.TimeUnit)7 BsonDocument (org.bson.BsonDocument)7 DeleteResult (com.mongodb.client.result.DeleteResult)6 HashMap (java.util.HashMap)6 ClientSessionOptions (com.mongodb.ClientSessionOptions)5 ReadConcern (com.mongodb.ReadConcern)5 Arrays (java.util.Arrays)5 BsonValue (org.bson.BsonValue)5 FullDocument (com.mongodb.client.model.changestream.FullDocument)4 InsertOneResult (com.mongodb.client.result.InsertOneResult)4 MongoClient (com.mongodb.reactivestreams.client.MongoClient)4 MongoCollection (com.mongodb.reactivestreams.client.MongoCollection)4