我正在使用Spring Boot v2.2.2.RELEASE
和Spring Data MongoDB
。在此示例中,我正在按部门代码分组执行,并让该组下的所有员工参加。
样本数据-
{
"firstName" : "Laxmi",
"lastName" : "Parate",
"email" : "[email protected]",
"createDate" : ISODate("2014-10-10T07:07:49.000Z"),
.........
.........
"status" : "A",
"departments" : {
"deptCd" : "A",
"deptName" : "Software Development",
"status" : "A",
}
}
如果我们可以使用Spring Data Repository Query做到这一点,那就太好了。
public interface EmployeeRepository extends CrudRepository<Employee, Object>{
@Query(value = "{}", fields = "{'departments': 1}")
Page<Employee> findAllGroupByDept(Pageable pageRequest);
}
至少我能够通过下面的查询获取数据,但是仍然难以以Pages的形式生成数据
db.country.aggregate([
{
$group: {
_id: "$departments.deptCd",
matches: { $push: '$$ROOT' }
}
}
])
参考:Keeping field in mongodb group by和how to group in mongoDB and return all fields in result