Search in sources :

Example 16 with Collation

use of org.springframework.data.mongodb.core.query.Collation in project spring-data-mongodb by spring-projects.

the class AbstractReactiveMongoQueryUnitTests method shouldApplyCollationParameter.

// DATAMONGO-1854
@Test
void shouldApplyCollationParameter() {
    Collation collation = Collation.of("en_US");
    // 
    createQueryForMethod("findWithCollationParameterByFirstName", String.class, Collation.class).executeBlocking(new Object[] { "dalinar", collation });
    ArgumentCaptor<Query> captor = ArgumentCaptor.forClass(Query.class);
    verify(withQueryMock).matching(captor.capture());
    assertThat(captor.getValue().getCollation()).contains(collation);
}
Also used : BasicQuery(org.springframework.data.mongodb.core.query.BasicQuery) Query(org.springframework.data.mongodb.core.query.Query) FindWithQuery(org.springframework.data.mongodb.core.ReactiveFindOperation.FindWithQuery) Collation(org.springframework.data.mongodb.core.query.Collation) Test(org.junit.jupiter.api.Test)

Example 17 with Collation

use of org.springframework.data.mongodb.core.query.Collation in project spring-data-mongodb by spring-projects.

the class AbstractReactiveMongoQueryUnitTests method shouldApplyDynamicAnnotatedCollationAsDocument.

// DATAMONGO-1854
@Test
void shouldApplyDynamicAnnotatedCollationAsDocument() {
    // 
    createQueryForMethod("findWithCollationUsingPlaceholderByFirstName", String.class, Object.class).executeBlocking(new Object[] { "dalinar", new Document("locale", "en_US") });
    ArgumentCaptor<Query> captor = ArgumentCaptor.forClass(Query.class);
    verify(withQueryMock).matching(captor.capture());
    assertThat(captor.getValue().getCollation().map(Collation::toDocument)).contains(Collation.of("en_US").toDocument());
}
Also used : BasicQuery(org.springframework.data.mongodb.core.query.BasicQuery) Query(org.springframework.data.mongodb.core.query.Query) FindWithQuery(org.springframework.data.mongodb.core.ReactiveFindOperation.FindWithQuery) Document(org.bson.Document) Collation(org.springframework.data.mongodb.core.query.Collation) Test(org.junit.jupiter.api.Test)

Example 18 with Collation

use of org.springframework.data.mongodb.core.query.Collation in project spring-data-mongodb by spring-projects.

the class AbstractReactiveMongoQueryUnitTests method collationParameterShouldOverrideAnnotation.

// DATAMONGO-1854
@Test
void collationParameterShouldOverrideAnnotation() {
    Collation collation = Collation.of("de_AT");
    // 
    createQueryForMethod("findWithWithCollationParameterAndAnnotationByFirstName", String.class, Collation.class).executeBlocking(new Object[] { "dalinar", collation });
    ArgumentCaptor<Query> captor = ArgumentCaptor.forClass(Query.class);
    verify(withQueryMock).matching(captor.capture());
    assertThat(captor.getValue().getCollation()).contains(collation);
}
Also used : BasicQuery(org.springframework.data.mongodb.core.query.BasicQuery) Query(org.springframework.data.mongodb.core.query.Query) FindWithQuery(org.springframework.data.mongodb.core.ReactiveFindOperation.FindWithQuery) Collation(org.springframework.data.mongodb.core.query.Collation) Test(org.junit.jupiter.api.Test)

Example 19 with Collation

use of org.springframework.data.mongodb.core.query.Collation 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 20 with Collation

use of org.springframework.data.mongodb.core.query.Collation in project spring-data-mongodb by spring-projects.

the class MongoTemplate method mapReduce.

@Override
public <T> MapReduceResults<T> mapReduce(Query query, String inputCollectionName, String mapFunction, String reduceFunction, @Nullable MapReduceOptions mapReduceOptions, Class<T> entityClass) {
    Assert.notNull(query, "Query must not be null!");
    Assert.notNull(inputCollectionName, "InputCollectionName must not be null!");
    Assert.notNull(entityClass, "EntityClass must not be null!");
    Assert.notNull(reduceFunction, "ReduceFunction must not be null!");
    Assert.notNull(mapFunction, "MapFunction must not be null!");
    String mapFunc = replaceWithResourceIfNecessary(mapFunction);
    String reduceFunc = replaceWithResourceIfNecessary(reduceFunction);
    MongoCollection<Document> inputCollection = getAndPrepareCollection(doGetDatabase(), inputCollectionName);
    // MapReduceOp
    MapReduceIterable<Document> result = inputCollection.mapReduce(mapFunc, reduceFunc, Document.class);
    if (query != null && result != null) {
        if (query.getLimit() > 0 && mapReduceOptions.getLimit() == null) {
            result = result.limit(query.getLimit());
        }
        if (query.getMeta() != null && query.getMeta().getMaxTimeMsec() != null) {
            result = result.maxTime(query.getMeta().getMaxTimeMsec(), TimeUnit.MILLISECONDS);
        }
        result = result.sort(getMappedSortObject(query, entityClass));
        result = result.filter(queryMapper.getMappedObject(query.getQueryObject(), Optional.empty()));
    }
    Optional<Collation> collation = query.getCollation();
    if (mapReduceOptions != null) {
        Optionals.ifAllPresent(collation, mapReduceOptions.getCollation(), (l, r) -> {
            throw new IllegalArgumentException("Both Query and MapReduceOptions define a collation. Please provide the collation only via one of the two.");
        });
        if (mapReduceOptions.getCollation().isPresent()) {
            collation = mapReduceOptions.getCollation();
        }
        if (!CollectionUtils.isEmpty(mapReduceOptions.getScopeVariables())) {
            result = result.scope(new Document(mapReduceOptions.getScopeVariables()));
        }
        if (mapReduceOptions.getLimit() != null && mapReduceOptions.getLimit().intValue() > 0) {
            result = result.limit(mapReduceOptions.getLimit());
        }
        if (mapReduceOptions.getFinalizeFunction().filter(StringUtils::hasText).isPresent()) {
            result = result.finalizeFunction(mapReduceOptions.getFinalizeFunction().get());
        }
        if (mapReduceOptions.getJavaScriptMode() != null) {
            result = result.jsMode(mapReduceOptions.getJavaScriptMode());
        }
        if (mapReduceOptions.getOutputSharded().isPresent()) {
            result = result.sharded(mapReduceOptions.getOutputSharded().get());
        }
    }
    result = collation.map(Collation::toMongoCollation).map(result::collation).orElse(result);
    List<T> mappedResults = new ArrayList<T>();
    DocumentCallback<T> callback = new ReadDocumentCallback<T>(mongoConverter, entityClass, inputCollectionName);
    for (Document document : result) {
        mappedResults.add(callback.doWith(document));
    }
    return new MapReduceResults<T>(mappedResults, new Document());
}
Also used : MapReduceResults(org.springframework.data.mongodb.core.mapreduce.MapReduceResults) Document(org.bson.Document) Collation(org.springframework.data.mongodb.core.query.Collation)

Aggregations

Collation (org.springframework.data.mongodb.core.query.Collation)33 Query (org.springframework.data.mongodb.core.query.Query)24 Test (org.junit.jupiter.api.Test)19 Document (org.bson.Document)15 Collectors (java.util.stream.Collectors)7 DataAccessException (org.springframework.dao.DataAccessException)7 BasicQuery (org.springframework.data.mongodb.core.query.BasicQuery)7 MongoException (com.mongodb.MongoException)6 WriteConcern (com.mongodb.WriteConcern)6 DeleteResult (com.mongodb.client.result.DeleteResult)6 UpdateResult (com.mongodb.client.result.UpdateResult)6 AggregationOptions (org.springframework.data.mongodb.core.aggregation.AggregationOptions)6 TypedAggregation (org.springframework.data.mongodb.core.aggregation.TypedAggregation)6 Criteria (org.springframework.data.mongodb.core.query.Criteria)5 MongoPersistentEntity (org.springframework.data.mongodb.core.mapping.MongoPersistentEntity)4 FullDocument (com.mongodb.client.model.changestream.FullDocument)3 java.util (java.util)3 Collection (java.util.Collection)3 Bson (org.bson.conversions.Bson)3 BeansException (org.springframework.beans.BeansException)3