Search code examples
mongodbmongodb-javamorphiamongo-java-driverdatabase

Having conditional multiple filters in Morphia query for Mongo database


Environment : MongoDb 3.2, Morphia 1.1.0

So lets say i am having a collection of Employees and Employee entity has several fields. I need to do something like apply multiple filters (conditional) and return a batch of 10 records per request.

pesudocode as below.

@Entity("Employee")
Employee{
 String firstname,
 String lastName,
 int salary,
 int deptCode,
 String nationality
}

and in my EmployeeFilterRequesti carry the request parameter to the dao

EmployeeFilterRequest{
 int salaryLessThen
 int deptCode,
 String nationality..
}

Pseudoclass

class EmployeeDao{

public List<Employee> returnList;

public getFilteredResponse(EmployeeFilterRequest request){
   DataStore ds = getTheDatastore();

   Query<Employee> query = ds.createQuery(Emploee.class).disableValidation();

   //conditional request #1
   if(request.filterBySalary){
     query.filter("salary >", request.salary);
   }

   //conditional request #2
   if(request.filterBydeptCode){
     query.filter("deptCode ==", request.deptCode);
   }

   //conditional request #3
   if(request.filterByNationality){
     query.filter("nationality ==", request.nationality);
   }

   returnList = query.batchSize(10).asList();

/******* **THIS IS RETURNING ME ALL THE RECORDS IN THE COLLECTION, EXPECTED ONLY 10** *****/
 }
}

SO as explained above in the code.. i want to perform conditional filtering on multiple fields. and even if batchSize is present as 10, i am getting complete records in the collection.

how to resolve this ???

Regards Punith


Solution

  • Blakes is right. You want to use limit() rather than batchSize(). The batch size only affects how many documents each trip to the server comes back with. This can be useful when pulling over a lot of really large documents but it doesn't affect the total number of documents fetched by the query.

    As a side note, you should be careful using asList() as it will create objects out of every document returned by the query and could exhaust your VM's heap. Using fetch() will let you incrementally hydrate documents as you need each one. You might actually need them all as a List and with a size of 10 this is probably fine. It's just something to keep in mind as you work with other queries.