0

How can i build this MongoDB query with Spring Criteria?

{
  $or: [
    { "$text" : { "$search" : "570-11024" } },
    {"productDetails.code": "572-R110"}
  ]
}

It combines a fulltext index search with normal Where criteria with an orOperator.

Query's orOperator(Criteria... criteria) method takes only Criteria and no TextCriteria and also no CriteriaDefinition interface.

2 Answers 2

1

Yeah you are right, in spring data mongo you could do this,

final TextCriteria textCriteria = TextCriteria.forDefaultLanguage().matchingAny("570-11024");
final DBObject tc = textCriteria.getCriteriaObject();
final Criteria criteria = Criteria.where("productDetails.code").is("572-R110");
final DBObject co = criteria.getCriteriaObject();

BasicDBList or = new BasicDBList();
or.add(tc);
or.add(co);

DBObject qq = new BasicDBObject("$or", or);
// Use MongoTemplate to execute command
mongoTemplate.executeCommand(qq);
Sign up to request clarification or add additional context in comments.

2 Comments

looks promising. any idea how to do this with reactive mongoTemplate?
textCriteria.getCriteriaObject returns a Document not DBObject.
0

Yes, you currently cannot use the Query's orOperator method to combine Criteria and TextCriteria. A workaround involves converting both the Criteria and TextCriteria objects to its Document representations, adding it to a BasicDbList and then converting back to a "$or" Criteria object.

TextCriteria textCriteria = TextCriteria.forDefaultLanguage().matchingAny("570-11024");
Criteria criteria = Criteria.where("productDetails.code").is("572-R110");

BasicDBList bsonList = new BasicDBList();
bsonList.add(criteria.getCriteriaObject());
bsonList.add(textCriteria.getCriteriaObject());

Query query = new Query();
query.addCriteria(new Criteria("$or").is(bsonList));
mongoTemplate.find(query, YourEntity.class);

PS: Someone has raised this issue in the spring-data-mongodb repo with a proposed fix by changing the parameter types of orOperator from Criteria to CriteriaDefinition.

https://github.com/spring-projects/spring-data-mongodb/issues/3895.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.