paul
paul

Reputation: 13481

Spring data mongo use OR in Query

Let´s see if somebody can help with this.

I want use Repository of Spring Data mongodb, and I want use Query annotation to filter the find by value A=10 or A=20

  @Query("{A: 10, A:20}")
  findById(int id);

Obiously "," try to make an AND, and I need an OR.

Any idea please?

Upvotes: 41

Views: 88221

Answers (9)

hellojava
hellojava

Reputation: 5064

Or if you are using a Criteria API

Criteria criteria = new Criteria();
criteria.orOperator(Criteria.where("A").is(10),Criteria.where("B").is(20));
Query query = new Query(criteria);

mongoOps.find(query, <Yourclass>.class, "collectionName");

Upvotes: 108

Yushi
Yushi

Reputation: 191

You can use Spring Data MongoDB like this:

Query query = new Query();
query.addCriteria(
    Criteria.where("").orOperator(
        Criteria.where("A").is(10),
        Criteria.where("B").is(20)
    )
);

mongoTemplate.find(query, YourClazz.class, "CollectionName");

Upvotes: 19

ismile47
ismile47

Reputation: 631

In addition to helloJava answer, If you already have query with other criteria's you can add orOperation directly on query.addCriteria as below.

query.addCriteria(new Criteria().orOperator(Criteria.where("fieldA").is(value),
                Criteria.where("fieldB").is(value2)));

Upvotes: 9

Ajay k
Ajay k

Reputation: 151

Query query = new Query();  
Criteria criteria = new Criteria();  
criteria.orOperator(Criteria.where("category").is("your_Value_Category"), 
    Criteria.where("parentCategory").is("your_Value_ParentCategory"));
query.addCriteria(criteria);
mongoTemplate.find(query, YourPersistenceClass.class);

Upvotes: 0

pama
pama

Reputation: 129

You can use the $in operator in Spring Java:

Criteria criteria = Criteria.where("field").in(listOfOptions);

Upvotes: 5

david
david

Reputation: 1057

Use Spring's BasicQuery:

DBObject queryCondition = new BasicDBObject();        
BasicDBList values = new BasicDBList();
values.add(new BasicDBObject("A", 10));
values.add(new BasicDBObject("B", 20));
queryCondition.put("$or", values);
Query query = new BasicQuery(queryCondition);
mongoTemplate.find(query, clazz);

Upvotes: 2

Ido Cohn
Ido Cohn

Reputation: 1705

You can use Spring's Query structure:

Query query = new Query();
query.addCriteria(Criteria.where("id").is(10).orOperator(Criteria.where("id").is(20));
this.client.findOne(query, clazz);

Upvotes: -3

FakeUser
FakeUser

Reputation: 468

I think this might work

@Query("{'$or':[ {'A':10}, {'B':20} ] }")

Upvotes: 38

JohnnyHK
JohnnyHK

Reputation: 312159

You can use the $in operator for that. I don't know Java Spring, but given your example, the Query part should look like:

@Query("{A: {$in: [10, 20]}}")

Upvotes: 2

Related Questions