user2180794
user2180794

Reputation: 1445

Java MongoDB search for value in multiple fields

i have a java method

 public List<Project> tagSearch(String searchCriteria){
    Query query = new Query();
    return mongoTemplate.find(query.addCriteria(Criteria.where("projectTag")
            .regex(searchCriteria,"i")), Project.class, COLLECTION_NAME);
}

here it is searching the searchCriteria value in the field projectTag. I want to search for that value in multiple fields. for example another field projectName

appreciate your assistance.

Upvotes: 1

Views: 3852

Answers (2)

Mohan
Mohan

Reputation: 741

You can use below code

final Criteria criteria = new Criteria();
criteria.orOperator(Criteria.where("projectTag").regex(searchCriteria, "i"),
                    Criteria.where("projectName").regex(searchCriteria, "i"));
final Query query = new Query(criteria);
final List<Project> projectEntities = mongoTemplate.find(query, Project.class);

Upvotes: 1

Faizal
Faizal

Reputation: 1345

Use orOperator

You can use as many criteria in orOperator. Then it will look like this :

Query query = new Query();
Criteria criteria1 = new Criteria().where("projectTag").regex(searchCriteria, "i");
Criteria criteria2 = new Criteria().where("projectName").regex(searchCriteria, "i");
query.addCriteria(new Criteria().orOperator(c1,c2));
return mongoTemplate.find(query, Project.class, COLLECTION_NAME);

Upvotes: 1

Related Questions