spring数据mongodb group by
我在我的项目中使用spring数据Mongodb,并在下面的类中引用我的查询来对结果进行分组:
学生class:
@Document(collection = "student") public class Student { @Id private String id; private String firstName; private String lastName; //other fields //getters & setters }
StudentResults(dto):
public class StudentResults { private String firstName; private List studentIds; //I need List here public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public List getStudentIds() { return studentIds; } public void setStudentIds(List studentIds) { this.studentIds = studentIds; } }
StudentServiceImpl类:
public class StudentServiceImpl implements StudentService { @Autowired private MongoTemplate mongoTemplate; public List findStudentsGroupByFirstName() { TypedAggregation studentAggregation = Aggregation.newAggregation(Student.class, Aggregation.group("firstName"). addToSet("id").as("studentIds"), Aggregation.project("studentIds"). and("firstName").previousOperation()); AggregationResults results = mongoTemplate. aggregate(studentAggregation, StudentResults.class); List studentResultsList = results.getMappedResults(); return studentResultsList; } }
使用上面的代码,我能够成功检索List studentIds
,但我需要使用Aggregation.group()
检索List students
? 你能帮我吗?
将TypedAggregation
部分更改为下方,并将StudentResults
字段添加到StudentResults
TypedAggregation studentAggregation = Aggregation.newAggregation(Student.class, Aggregation.group("firstName"). push("$$ROOT").as("students"));
$$ ROOT将推送整个文档。
更新:
TypedAggregation studentAggregation = Aggregation.newAggregation(Student.class, Aggregation.group("firstName"). push(new BasicDBObject ("_id", "$_id").append ("firstName", "$firstName").append ("lastName", "$lastName")).as("students"));
- Java中的接口数组
- JavaFX ControlFX对话框中的Action Buttons css样式
- 具有身份validation的Spring Boot项目结构
- 使用Oltu传递给OAuthTokenRequest时无法使用@ Context HttpServletRequest检索发布数据
- 如何使用apache spark的MLlib的线性回归?
- 在JsonDeserializer中自动assembly:SpringBeanAutowiringSupport与HandlerInstantiator
- 从数据库中检索一行作为Hibernate中的Map
- 推荐的Maven存储库搜索引擎?
- 如何使用Hibernate插入新项目?