mongodb分组查询后按照日期最大值取数

需求:按照数据代码分组获取最新日期的每一条记录

mongoTemplate语句:
  List operations = new ArrayList<>();
  //查询条件
        operations.add(Aggregation.match(Criteria.where("CODE").in(windCodes)));
		//分组条件
        operations.add(Aggregation.group("CODE")
		//按照日期最大值拿
                .max("TRADE_DT").as("tradeDate").first("AA").as("aa")
        );
        operations.add(Aggregation.sort(Sort.Direction.DESC, "tradeDate"));
        Aggregation aggregation = Aggregation.newAggregation(operations);
		//mongo文档名字
        AggregationResults g = mongoTemplate.aggregate(aggregation, "mongo文档名字", BasicDBObject.class);
		//g中有所有数据

nosql语句:

db.getCollection("ashareeodprices").aggregate([

                {$match:{"CODE":{$in:["code1","code2"]}}},
        {$group:{
            _id:"$CODE",
                    TRADE_DT:{$max:"$TRADE_DT"},
            data:{$max: '$$ROOT'}
        }
        },
        {$project:{_id:1,CODE:1,TRADE_DT:1}}
])

$match 是查询条件

$group 分组  , _id是分组字段

TRADE_DT是每组里面的最大值

data:返回最大值的数据

$project 控制显示字段  例如 _id:1    1 显示 0 不显示

 

你可能感兴趣的:(java,mongodb)