MongoDB 聚合 分组 切分($Slice) 取值

268 阅读1分钟
db.collection.aggregate([
            {$match: {matchFeild: matchValue,}},
            { "$sort": { "sortFeild": -1 } },
            //根据分组$$ROOT
            {$group:{_id:"$gid",items:{$push:"$$ROOT"}}},
            { "$project": {
                //切分 取前两条
                    "items": {"$slice": [ "$items", 2 ] }
            }},
            {
                "$project": {
                    "items._id": 0,
                }
            }
        ])

// mongo db
MatchOperation match = Aggregation.match(new Criteria(ContentInfo.CIRCLE_ID).in(1122, 1111));
GroupOperation as = Aggregation.group("Group").push("$$ROOT").as("items"); ProjectionOperation as1 = Aggregation.project().and(ArrayOperators.Slice.sliceArrayOf("items").itemCount(2)).as("newItems");
Aggregation customerAgg = Aggregation.newAggregation(match, as, as1); mongoTemplate.aggregate(customerAgg, "collectionName", Map.class);