繁体   English   中英

在Morphia查询Mongo数据库中使用条件多个过滤器

[英]Having conditional multiple filters in Morphia query for Mongo database

环境:MongoDb 3.2,Morphia 1.1.0

因此,可以说我有一个Employees集合,并且Employee实体具有多个字段。 我需要做一些事情,例如应用多个过滤器(有条件的)并为每个请求返回一批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,我仍在集合中获取完整的记录。

如何解决这个问题?

关于普尼思

布雷克是对的。 您要使用limit()而不是batchSize() 批处理大小仅影响每次访问服务器返回的文档数量。 当移出许多非常大的文档时,这很有用,但不会影响查询获取的文档总数。

附带说明一下,您应谨慎使用asList()因为它将从查询返回的每个文档中创建对象,并且可能耗尽VM的堆。 使用fetch()可以让您根据需要逐步添加文档。 您可能实际上需要将它们全部作为一个列表,并且大小为10可能很好。 在处理其他查询时,请记住这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM