springmongodbspring-bootmongodb-querymongorepository

How to build custom query in Spring boot for mongodb repository with $and and $or clause?


How to build a custom query for mongodb(using mongodb template) for the following query in Spring boot?

db.getCollection('collectionName').find(
   {$or:[
    {$and:[{"name":"xyz"},{"address:"1234"}]},
    {$and:[{"name":"abc"},{"address":"001"}]},
    {..}
    {..so on..}
    ]})

Can we use Criteria Query to query this?


Solution

  • You can build your query in this way:

    Criteria criteria = new Criteria();
    criteria.orOperator( 
        Criteria.where("name").is("xyz").and("address").is("1234"),
        Criteria.where("name").is("abc").and("address").is("001"),
        Criteria.where(...),
        Criteria.where(...)
    );
    Query query = new Query(criteria);
    mongoTemplate.find(query, YourClass.class, "CollectionName");
    

    If the number of criteria that you have to use is not fixed, you can populate a list of Criteria and pass it to the orOperator function:

    List<Criteria> criterias = new ArrayList<>();
    for (...) {
        //populate list
        criterias.add(Criteria.where(...).is(...).and(...).is(...);
    }
    Criteria criteria = new Criteria();
    criteria.orOperator(criterias);