2016-03-08 48 views
0

环境:MongoDB的3.2,吗啡1.1.0具有吗啡查询条件的多个过滤器Mongo的数据库

因此,可以说我有员工的收集和雇员实体有几个领域。我需要执行一些操作,例如应用多个过滤器(有条件),并为每个请求返回一批10条记录。

pesudocode如下。

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

在我EmployeeFilterRequest i中的请求参数携带于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** *****/ 
} 
} 

SO如所解释..我想在执行条件滤波多个领域。即使批量大小为10,我也会收集完整的记录。

如何解决这个???

问候 Punith

+1

我认为你是错把'.batchSize()''为.limit()',这是两个不同的东西。 –

+0

谢谢@BlakesSeven !!这解决了:) –

回答

1

布雷克是正确的。您想要使用limit()而不是batchSize()。批量大小只影响每次到达服务器的文档数量。这在拉取大量非常大的文档时非常有用,但不会影响查询获取的文档总数。

作为一个侧面说明,你应该使用asList()小心,因为它会创建了该查询返回的每个文档的对象,并可能耗尽你的虚拟机的堆。使用fetch()可让您逐步补充文档,因为您需要每个文档。你可能实际上需要他们所有的一个列表和大小为10这可能是好的。当您处理其他查询时,请记住这一点。

+0

谢谢@evanchooly!这解决了:)。我会照顾给出的建议 –

相关问题