Mongodb Java驱动程序在聚合查询中使用限制

时间:2015-07-03 12:22:54

标签: java mongodb aggregation-framework spring-data-mongodb

问题

查询工作正常,但没有限制和跳过,它一次获取所有记录。

请建议我做错了什么。

MongoDB Collection

 {  
      "_id" : ObjectId("559666c4e4b07a176940c94f"),     
      "postId" : "559542b1e4b0108c9b6f390e",    
     "user" : {         
                 "userId" : "5596598ce4b07a176940c943",         
                 "displayName" : "User1",       
                 "username" : "user1",      
                 "image" : ""   
      },    
      "postFor" : {         
                     "type": "none",
                      "typeId" : ""     
      },    
     "actionType" : "like",     
     "isActive" : 1,
     "createdDate" : ISODate("2015-07-03T10:41:07.575Z"),   
     "updatedDate" : ISODate("2015-07-03T10:41:07.575Z") 
}

Java驱动程序查询

 Aggregation aggregation = newAggregation(                                

      match(Criteria.where("isActive").is(1).and("user.userId").in(feedUsers)),
      group("postId")
      .last("postId").as("postId")
      .last("postFor").as("postFor")
      .last("actionType").as("actionType")
      .last("isActive").as("isActive")
      .last("user").as("user")
      .last("createdDate").as("createdDate")
      .last("updatedDate").as("updatedDate"),
      sort(Sort.Direction.DESC, "createdDate")
    );
aggregation.skip( skip );
aggregation.limit( limit );
AggregationResults<UserFeedAggregation> groupResults =
mongoOps.aggregate(aggregation, SocialActionsTrail.class, UserFeedAggregation.class);
return groupResults.getMappedResults();

由于

1 个答案:

答案 0 :(得分:3)

聚合管道是&#34;顺序&#34;在运作中。这些与.find() .sort() .limit()是&#34;修饰符&#34;到查询操作:

.skip()

除非您在&#34;序列&#34;中定义操作。然后管道不知道执行的顺序。因此,将管道定义为一个整体。

一个基本的例子:

Aggregation aggregation = newAggregation(                               
    match(Criteria.where("isActive")
        .is(1).and("user.userId").in(feedUsers)),
    group("postId")
        .last("postId").as("postId")
        .last("postFor").as("postFor")
        .last("actionType").as("actionType")
        .last("isActive").as("isActive")
        .last("user").as("user")
        .last("createdDate").as("createdDate")
        .last("updatedDate").as("updatedDate"),
    sort(Sort.Direction.DESC, "createdDate"),
    skip( skip ),
    limit( limit )
);

输出完美的管道:

Aggregation aggregation = newAggregation(
    group("postId"),
    skip(1),
    limit(1)
);

System.out.println(aggregation)

请参阅核心文档中的$skip$limit