0

环境:MongoDb 3.2,Morphia 1.1.0

所以可以说我有一个员工集合,员工实体有几个字段。我需要做一些事情,比如应用多个过滤器(有条件的)并为每个请求返回一批 10 条记录。

伪代码如下。

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

在我的EmployeeFilterRequest我将请求参数带到 dao

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

伪类

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** *****/
 }
}

所以如上面代码中的解释..我想对多个字段执行条件过滤。即使 batchSize 为 10,我也会在集合中获得完整的记录。

如何解决这个???

问候普尼斯

4

1 回答 1

1

布莱克斯是对的。你想使用limit()而不是batchSize(). 批量大小仅影响每次访问服务器返回的文档数量。这在提取大量非常大的文档时很有用,但不会影响查询获取的文档总数。

附带说明一下,您应该小心使用asList(),因为它会从查询返回的每个文档中创建对象,并且可能会耗尽 VM 的堆。使用fetch()将使您可以根据需要逐步补充文档。您实际上可能需要将它们全部作为一个 List 并且大小为 10 这可能没问题。在处理其他查询时,请记住这一点。

于 2016-03-08T13:41:07.623 回答