mongoTemplate Aggregation

来源:互联网 发布:程序员老公的好处 编辑:程序博客网 时间:2024/06/05 19:56

可以通过以下声明方式进行使用

TypedAggregation<User> agg = Aggregation.newAggregation(User.class);AggregationResults<BasicDBObject> aggregationResults = mongoTemplate.aggregate(agg, BasicDBObject.class);  //BasicDBObject可以替换成对应的model类
Aggregation agg = Aggregation.newAggregation(User.class);AggregationResults<BasicDBObject> aggregationResults = mongoTemplate.aggregate(agg, User.class, BasicDBObject.class);

示例:

Aggregation.newAggregation(User.class,                match(criteria),                group("id", "infoList"), // { "$group" : { "_id" : { "id" : "$id" , "infoList" : "$infoList"}}}                unwind("infoList"), //{ "$unwind" :"$_id.infoList"}                project("id", "infoList"), // { "$project" : { "id" : "$_id.id", "infoList" : "$_id.infoList"}}                group("infoList.date").addToSet(                "infoList.timeSlot").as("timeSlots"),                project("timeSlots").and("time")               .previousOperation()                                                                                                                   );//其他: 如果先使用group 再用project时/* group("id", "infoList"),  unwind("infoList"),  project("id").and("infoList") .previousOperation() .andInclude("infoList")  // {"$project" : { "id" : "$_id.id" , "_id" : 0 , "infoList" : "$_id.infoList"}}  *//*project("id").and("infoList").previousOperation().andInclude("infoList", "id") //.previousOperation()表示使用"infoList": "$_id", 此时 "_id" : 0, 继续使用.andInclude("infoList", "id")则表示 "infoList" : "$_id.infoList", "id": "$_id.id"; 如果and(name) name未被使用则会变成name会单独作为key,且值为"$_id"*/