Criteria criteria = new Criteria(); if (userId != null && userId > 0) { criteria.orOperator(Criteria.where("device_id").is(deviceId), Criteria.where("uid").is(userId)); } else { criteria.and("device_id").is(deviceId).and("uid").is(0); } Aggregation agg = Aggregation.newAggregation( Aggregation.match(criteria), new GroupOperation(Aggregation.fields("vid")).last("$$ROOT").as("data"), Aggregation.project("data.vid", "data.lastmodified"), Aggregation.sort(Sort.by(Sort.Direction.DESC, "lastmodified")), Aggregation.skip(new Long(start)), Aggregation.limit(limit) ); AggregationResults<Document> likeVideoAggregationResults = mongoTemplateFacade.getMongoUserVideoTemplate().aggregate(agg, "like_video", Document.class); List<String> vids = new ArrayList<>(); for (Iterator<Document> iterator = likeVideoAggregationResults.iterator(); iterator.hasNext(); ) { Document obj = iterator.next(); vids.add((String) obj.get("_id")); }