@Document
public class Goods implements Serializable {
@Id
private String id;
private String name;
private String price;
private String description;
private String max;
private String num;
private String[] pictures;
private String subMchId;
private String tag;
private List<Info> infos;
public Goods(String id, String name, String price, String description, String max, String num, String[] pictures, String subMchId, String tag, List<Info> infos) {
this.id = id;
this.name = name;
this.price = price;
this.description = description;
this.max = max;
this.num = num;
this.pictures = pictures;
this.subMchId = subMchId;
this.tag = tag;
this.infos = infos;
}
}
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapreduce.GroupBy;
import org.springframework.data.mongodb.core.mapreduce.GroupByResults;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Log4j2
@RestController
public class GoodsController {
@Autowired
private MongoTemplate mongoTemplate;
@GetMapping(value = {"module"})
public ResponseEntity<GroupByResults> module() throws Exception {
GroupBy groupBy = new GroupBy("tag").initialDocument("{ collection: [] }").reduceFunction("function (doc,pre){pre.collection.push({id:doc._id.str,name:doc.name,pictures:doc.pictures});}");
GroupByResults groupByResults = mongoTemplate.group("goods", groupBy, Goods.class);
return new ResponseEntity<GroupByResults>(groupByResults, HttpStatus.OK);
}
}
[
{
"id":"5cd392bbb53ac62ba8e8593f",
"name":"苹果",
"price":"12.99",
"description":"苹果家庭的低调皇室",
"max":"5",
"num":"5",
"pictures":[],
"subMchId":"S0000001",
"tag":"精选水果",
"infos":null
},
{
"id":"5cd393dcb53ac61810a67b8e",
"name":"苹果",
"price":"12.99",
"description":"苹果家庭的低调皇室",
"max":"5",
"num":"5",
"pictures":[],
"subMchId":"S0000001",
"tag":"精选水果",
"infos":null
},
{
"id":"5cd39512b53ac60b905d8602",
"name":"苹果",
"price":"12.99",
"description":"苹果家庭的低调皇室",
"max":"5",
"num":"5",
"pictures":[],
"subMchId":"S0000001",
"tag":"新鲜蔬菜",
"infos":null
}
]
{
"rawResults":{
"retval":[
{
"tag":"精选水果",
"collection":[
{
"id":"5cd392bbb53ac62ba8e8593f",
"name":"苹果",
"pictures":[]
},
{
"id":"5cd393dcb53ac61810a67b8e",
"name":"苹果",
"pictures":[]
}
]
},
{
"tag":"新鲜蔬菜",
"collection":[
{
"id":"5cd39512b53ac60b905d8602",
"name":"苹果",
"pictures":[]
}
]
}
],
"count":3,
"keys":2,
"ok":1
},
"count":3,
"keys":2,
"serverUsed":null
}
网友评论