如何使用聚合类将我现有的mongo db查询转换为spring boot

时间:2017-06-27 11:51:33

标签: java spring mongodb spring-boot

我写过mongodb查询。我在使用聚合类在春季启动时转换它时面临一些问题。所以,请帮助我,我希望它使用聚合类在spring boot中转换它。

 jenkins@jenkins_host $ ssh-keyscan -H bitbucket.com >> ~/.ssh/known_hosts

以下是数据库查询响应

db.api_audit.aggregate([{

  $match: {
      merchant_id: '015994832961',
      request_time: {$gte: ISODate("2017-05-11T00:00:00.0Z"), 
          $lt: ISODate("2017-05-12T00:00:00.0Z")}}},
{  
   $group: 
    {
        _id: {
        SERVICE_NAME: "$service_name",

        STATUS: "$status"
    },
    count: {
        "$sum": 1
    }
}
}, {


 $group: {
    _id: "$_id.SERVICE_NAME",

    STATUSCOUNT: {
        $push: {
            Service_name: "$_id.STATUS",
            count: "$count"
        }
    }
}
 },
 { $sort : { "STATUSCOUNT.count" : -1} }
  ])

提前致谢。

1 个答案:

答案 0 :(得分:2)

首先,您创建所有必需的操作,然后将它们添加到聚合管道。然后你把它喂给一个自动装配的mongotemplate。

这样的事情:

@Autowired
private final MongoTemplate mongoTemplate;

void aggregate()
{

    Criteria match = where("merchant_id").is("015994832961").andOperator(where("request_time").gte(Date.parse("2017-05-11T00:00:00.0Z")).lt(Date.parse("2017-05-11T00:00:00.0Z")));
    GroupOperation groupOperation1 = group(fields().and("SERVICE_NAME").and("STATUS")).count().as("count");
    GroupOperation groupOperation2 = ...//(not sure how push works here, but it should not be hard to figure out)
    SortOperation sortOperation = sort(DESC, "STATUSCOUNT.count");

    Aggregation aggegation = Aggregation.newAggregation(match, groupOperation1, groupOperation2, sortOperation);

    List<Result> results = mongoTemplate.aggegate(aggregation, ObjectOfCollectionToRunOn.class, Result.class).getMappedResults();
}