Reputation: 13481
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
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
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
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
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
Reputation: 129
You can use the $in operator in Spring Java:
Criteria criteria = Criteria.where("field").in(listOfOptions);
Upvotes: 5
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
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
Reputation: 468
I think this might work
@Query("{'$or':[ {'A':10}, {'B':20} ] }")
Upvotes: 38