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

143
Visualizações
Creating Query like "A is "b" and C is '' " (Spring Boot/Spring Data w/Mongo)

I'm making a simple application with Spring Boot (2.3.4) using MongoDB with Spring Data for MongoDB. I usually create queries for the app using the @Query annotation and it works very fine. But for an Aggregation I want to use, I built a query with the Criteria class. The criteria I need is like

where("primary").is(value).and("secondary").is("").

I need all entries where primary is equal to 'value' and secondary is empty. The query entered in MOngoDB Compass

{ $and: [ { primary: 'value' }, { secondary: ''} ] }

works as expected, but when I try to use the Criteria with Spring, it looks like the and part with the secondary is completely dropped. I get any results with 'value' in primary and with anything in secondary. This means an empty fields or anything else. Replacing the .is("") part with .regex("^$") didn't help.

This looks pretty basic to me, so what am I missing here? I don't want to replace the empty secondary with an "empty flag", because that feels wrong.

Update:

This is the code in question

Criteria crit;
if(!primary.equals(secondary)) {
    crit = where("primary").is(primary.name()).and("secondary").is(secondary.name());
} else {
    crit = where("primary").is(primary.name()).and("secondary").is("");
}
MatchOperation matchStage = Aggregation.match(crit);
GroupOperation groupStage = Aggregation.group("grouping").count().as("sum");
SortOperation sortStage = new SortOperation(Sort.by("_id"));

Aggregation aggregation = Aggregation.newAggregation(matchStage, groupStage, sortStage);
AggregationResults<TypePerGroup> results =  mongoTemplate.aggregate(aggregation, "dataCollection",  TypePerGroup.class);
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

This works with mongodb - Not sure what abstraction compass adds. Both queries don't generate the same json query but they are equal.

Generated query

where("primary").is(value).and("secondary").is(""). 

is

{"primary":value, "secondary": ""}

Perhaps compass doesn't like this variant ?

Anyways to generate query similar to what you have you input in compass you can use below code

Criteria criteria = new Criteria();
criteria.andOperator(Criteria.where("primary").is("hello"), Criteria.where("secondary").is(""));
Query query = Query.query(criteria);
over 4 years ago · Santiago Trujillo Relatório

0

You are not missing anything. where("primary").is(value).and("secondary").is("") is correct and is functionally equivalent to { $and: [ { primary: 'value' }, { secondary: ''} ] }. You should turn on debug level logging for MongoTemplate to see the generated query.

over 4 years ago · Santiago Trujillo Relatório

0

A have connected to Atlas using Mongo DBCompas and added 4 records to collection:

[{
  "primary": "A",
  "secondary": "A"
},{
  "primary": "A",
  "secondary": ""
},{
  "primary": "B",
  "secondary": "B"
},{
  "primary": "B",
  "secondary": ""
}]

both queries:

    List<Data> firstResults = mongoTemplate.query(Data.class)
            .matching(Query.query(Criteria.where("primary").is("B").and("secondary").is("")))
            .all();
    System.out.println(firstResults);

    Criteria criteria = new Criteria();
    criteria.andOperator(Criteria.where("primary").is("B"), Criteria.where("secondary").is(""));
    List<Data> secondResults = mongoTemplate.query(Data.class)
            .matching(Query.query(criteria))
            .all();
    System.out.println(secondResults);

gave the same result:

[Data{primary='B', secondary=''}]

Campfire can you please provide example of your code to analyze?

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