Home > Blockchain >  Can somebody help me building up an @Query that can be used with MongoDB
Can somebody help me building up an @Query that can be used with MongoDB

Time:01-23

I have laid out the Java architecture according to my requirement but is struggling with the formation of query part.

The architecture is as follows

Class AbcRequest{
List<Filters> filters;
}

Class Filters{
String abcCode;
List<String> abcType;
}

Class abcController{
getFilters(List<String>someList, boolean status, AbcRequest request){
for(Filters filter: request.getFilters(){
String abcCode = filter.getAbcCode();
List<String> abcTypes = filter.getAbcType();
  }
 }
}

Now I want to pass these values to a repository and get the list of required queries from DB based on it.

My query should have a condition like : where ((someList in ('a','b') and status='false' and abcCode='8' and abcType in ('done','pending') OR (someList in ('a','b') and status='false' and abcCode='6' and abcType in ('pending'))

How to write a MongoDB @Query to get such a query out of the repository method. It is a mixture of many 'AND' along with combination of 'OR' Like for example :-- where (a AND b AND c AND d) OR (a AND e AND f AND d)

I know how to use simple OR with @Query:- Like building a query for example (where A=10 OR B=10) @Query('$or' : [{A:10},{B:10}])

But query that I wanted to build is a bit complex and am struggling with it. Also I don't want to use Criteria because I have to deal with return types. Best is to use @Query and I have been instructed to use @Query as well.

Any help will be much appreciated.

CodePudding user response:

Mayme you can try this:

Query query = new Query();
        Criteria criteria = new Criteria();
        Criteria a = new Criteria();
        a.andOperator(Criteria.where("someList").in(Arrays.asList("A","B")),Criteria.where(
                "status").is(false),Criteria.where("abcCode").is(6),....)
        // B is the same as a
        Criteria b = new Criteria();
        //...
        
        criteria.orOperator(a,b);
        query.addCriteria(criteria);

CodePudding user response:

I found a very good link to answer my own question : writing complex query in mongo DB

This will help with writing complex queries using @Query annotation for MongoDB.

This will also provide a vivid understanding of how to use AND and OR. Thanks!

  •  Tags:  
  • Related