您的位置:首页 > 数据库 > Mongodb

mongodb mongotemplate聚合

2016-03-24 16:05 465 查看
1.group by并且计算总数

  @Test
public void insertTest() {
//测试数据
//insertTestData();
Aggregation agg = Aggregation.newAggregation(
//Aggregation.match(Criteria.where("groupId").is(5)),
Aggregation.group("groupId").count().as("total"),
Aggregation.project("total").and("groupId").previousOperation(),
Aggregation.sort(Sort.DEFAULT_DIRECTION, "total"));
List<StaCount> list = mongoTemplate.aggregate(agg, "currentUser", StaCount.class).getMappedResults();
for(StaCount count : list) {
System.out.println(count.getGroupId() + ":" + count.getTotal());
}
  }
如果要带其他字段,将红字变为 Aggregation.group("groupId","groupName"...),并将project的and部分去掉即可;



2.Crieria的使用,注意andOperator和orOperator的用法

Aggregation agg = Aggregation.newAggregation(   Aggregation.match(new Criteria().andOperator(Criteria.where("onlineTime").gt(new Date()))   .orOperator(   Criteria.where("offlineTime").gt(new Date())   ,Criteria.where("offlineTime").exists(false) ))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: