Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

448
Visualizações
Use $strLenCP with Spring Data MongoDB

I have this mongodb query

db.getCollection('myCollection').aggregate(
    [{
        $project: {
            length: {
                $strLenCP: "$prefix"
            }
        }
    }, {
        $sort: {
            length: -1
        }
    }]
)

that I want to use into a spring java project but I can't manage to write the correct java code (the sort is not the issue).

I tried this

Aggregation agg = newAggregation(project().andExpression("strLenCP(prefix)").as("prefixLength"));
AggregationResults < RequestSettingsWithPrefixLength > results = mongoTemplate.aggregate(agg, RequestSettings.class, RequestSettingsWithPrefixLength.class);
List < RequestSettingsWithPrefixLength > requestSettingsList = results.getMappedResults();

but I am getting a null key in agg JSON (debug mode):

{
    "aggregate": "__collection__",
    "pipeline": [{
        {
            "$project": {
                "prefixLength": {
                    "null": ["$prefix"]
                }
            }
        }]
    }
}

I can see that my agg object has this projection operation:

expression -> strLenCP(prefix)
field -> AggregationField: AggregationField - name: prefixLength,  target: prefixLength, synthetic: true
params -> []

I am not sure this is correct but I can't find any documentation that uses strLenCP. I only found this test that uses the strLenCP projection: https://github.com/spring-projects/spring-data-mongodb/blob/dc57b66adfd60b4d69d1d349b4fcfa4ab0da95e7/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/SpelExpressionTransformerUnitTests.java#L922

Could someone help please?

Cheers

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

The support for Mongo3.4 aggregation operators were added in 1.10.0.RC1. If you are okay with updating to release candidate version everything should just work fine.

Or you can try the following but you'll need to use 1.8.5 version.

 Aggregation aggregation = newAggregation(
  project().and(new AggregationExpression() {
      @Override
      public DBObject toDbObject(AggregationOperationContext aggregationOperationContext) {
          return new BasicDBObject("$strLenCP", "$prefix");
      }
  }).as("prefixLength")
 );
over 4 years ago · Santiago Trujillo Relatório

0

You can use expression project(...).and(valueOf("fieldName").lengthCP()).as("fieldLength")

over 4 years ago · Santiago Trujillo Relatório

0

@kairius answer isn't clear. This is how it should be done: Use StringOperators#valueOf followed by lengthCP():

TypedAggregation.project()
    .and(StringOperators.valueOf("prefix").lengthCP())
    .as("length")
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda