运维开发网

mongodb操作

运维开发网 https://www.qedev.com 2020-05-09 16:42 出处:网络 作者:运维开发网整理
Criteria cri = Criteria.where("schoolId").is(gxyJobEntity.getShoolId()); Aggregation agg = Aggregation.newAggregation( Aggregation.match(cri), Aggregation.pro
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字段
0

精彩评论

暂无评论...
验证码 换一张
取 消