mongodb操作

Criteria cri = Criteria.where("schoolId").is(gxyJobEntity.getShoolId());

Aggregation agg = Aggregation.newAggregation( Aggregation.match(cri), Aggregation.project("memberId","attendenceTime","address"), Aggregation.group("memberId").max("attendenceTime").as("attendenceTime") ); List<MongoMoguAttendenceDto> result =template.aggregate(agg,"mogu_attendance",MongoMoguAttendenceDto.class).getMappedResults();

  mongdb 查询: 

db.mogu_attendance.aggregate([
{ "$match":{ "schoolId" : "f11c8ea12f457dbc19c768a8bb6357f8"}} ,
{ "$project":{address:1,memberId:1,attendenceTime:1, schoolId:1,userId:1}},
{ "$group" : { "_id" : "$memberId" ,"attendenceTime" : { "$max" : "$attendenceTime"}}}])

类似于: select memberId as _id , max(attendenceTime) as attendenceTime from mogu_attendance group by memberId where schoolId='f11c8ea12f457dbc19c768a8bb6357f8';

 

查询某个学校 每个学生(memberId是学生id) 最后一次考勤的时间。

输出:

/* 1 */
{
    "_id" : "ffd56c4f63f20adbbc7c88fe6dc26353",
    "attendenceTime" : ISODate("2019-08-31T10:00:00.000Z")
}

/* 2 */
{
    "_id" : "11c21ada808fb8a9bcb32aade1a5b61e",
    "attendenceTime" : ISODate("2019-08-22T05:59:28.646Z")
}

  在实体类 

MongoMoguAttendenceDto
总包括两个字段:
public class MongoMoguAttendenceDto implements Serializable {
	private static final long serialVersionUID = 1L;

	/**
	 * 唯一主键
	 */
	@Id
	private String attendanceId;
	/**
	 * 用户id
	 */
	private String userId;
	……
	/**
	 * 考勤时间
	 */
	private Date attendenceTime;

	private String backup;

  则把 查询结果的 _id 取值 memberId , 作为主键,并且 映射给 MongoMoguAttendenceDto 实体对象的 attendanceId , 

max("attendenceTime").as("attendenceTime")  把 attendenceTime字段 映射给  MongoMoguAttendenceDto 实体 的attendenceTime字段




select * from mogu_attendance where memberId='edcff6ee12daf586a27f7ad6cdb9814f' order by attendenceTime desc limit 1;
相当于:
db.getCollection('mogu_attendance').find({ "memberId" : "edcff6ee12daf586a27f7ad6cdb9814f"}).sort({"attendenceTime":-1}).limit(1)
java语句:
            Sort sort =null;
            sort = new Sort(Sort.Direction.DESC,"attendenceTime");
            Query query = new Query();
            Criteria cri = Criteria.where("memberId").is(gxyJobEntity.getStudentId());
            query.addCriteria(cri);
            List<MongoMoguAttendenceDto> result =template.find(query.with(sort).limit(1),MongoMoguAttendenceDto.class);

  或者:MongoMoguAttendenceDto result =template.findOne(query.with(sort).limit(1),MongoMoguAttendenceDto.class);

posted @ 2019-08-24 13:01  zhoudingzhao  阅读(168)  评论(0编辑  收藏  举报