Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 813
paul Avatar asked May 10 '13 08:05

paul


People also ask

Can we use spring data JPA with MongoDB?

Yes, DataNucleus JPA allows it, as well as to many other databases.

Which is better MongoTemplate or MongoRepository?

So I'd say that MongoTemplate is a better option, unless you have a very elaborated POJO model or need the custom queries capabilities of MongoRepository for some reason. Good points/examples. However your race condition example and undesired result can be avoided using @Version to prevent that very scenario.

How do I create a custom query in Mongo Repository?

We can use the @Query annotation to specify a custom query to declare a method of custom Repository. It works equally well with MongoDB as it does with JPA. However, the only difference is that in case of MongoDB, @Query takes a JSON query string instead of a JPA query.

How does MongoRepository work?

MongoRepository extends the PagingAndSortingRepository and QueryByExampleExecutor interfaces that further extend the CrudRepository interface. MongoRepository provides all the necessary methods which help to create a CRUD application and it also supports the custom derived query methods.


2 Answers

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"); 
like image 106
hellojava Avatar answered Sep 28 '22 01:09

hellojava


I think this might work

@Query("{'$or':[ {'A':10}, {'B':20} ] }") 
like image 33
FakeUser Avatar answered Sep 28 '22 02:09

FakeUser