mongo很难用, 主要是因为不习惯写很多字
文档写得很不错.
https://docs.mongodb.com/manual/reference/aggregation-variables/#agg-system-variables
https://docs.mongodb.com/manual/reference/operator/aggregation/sort/index.html
https://docs.mongodb.com/manual/reference/operator/aggregation/group/index.html
这篇写得也还可以.
https://www.jianshu.com/p/206f036bdfc5
对应springboot 中mongtemplate, 就是这样写
这个写得很不错
https://kb.objectrocket.com/mongo-db/mongodb-group-by-multiple-fields-using-aggregation-function-464
db.sales.aggregate( [ { $sort: { item: -1, date: -1 } }, { $group: { _id: "$item", firstSalesDate: { $first: "$date" }, firstId: { $first: "$_id" }, firstRoot: { $first: "$$ROOT" }, } } ] )
Criteria criteria = Criteria.where("xxx").is("xxxx").and("xxx").is(xxx);
Aggregation aggregation = Aggregation.newAggregation( Aggregation.match(criteria), Aggregation.sort(Sort.Direction.ASC, "createTime"), Aggregation.group("xx", "xx") .first("$id").as("xx") .first("$xxx").as("xx") .first("$xxx").as("xx") .first("$xxxx").as("xx") .first("$xxxx").as("xx") .first("$xxxx").as("xx") );
stackflow上的一段
--------------------------------------------------------------------------
Aggregation agg = newAggregation( //
match(where("hotelCode").is("0360")), //
sort(Direction.DESC, "confirmationNumber", "timestamp"), //
group("confirmationNumber") //
.first("timestamp").as("timestamp") //
.first(Aggregation.ROOT).as("reservationImage") //
);
--------------------------------------------------------------------------
比较坑的是, $_id在 mongotemplate里叫做$id, 少了_, 还有 Aggregation.ROOT, Aggregation.CURRENT