Mongo聚合查询到java

时间:2017-04-27 05:38:14

标签: java mongodb-query mongodb-java mongo-java-driver

我有以下聚合查询。对mongo世界来说是新手。有人可以帮助我将其转换为等效的JAVA查询。

  db['mnocollection'].aggregate([
    { $match : { $and : [ {"stId" : { "$gte" : 1 }}, {"stId" : { "$lte" :
          410 }} ] } },
    {$sort: { "objId" : -1 }},
    {$group:
             {
               _id : "$objId",
                "maxstId" : {$max: "$stId" },
                "idVal" : {$first : "$_id"}
             }},
              {$project: {  idVal : 1, _id : 0, maxstId : 1}},
          { $skip: 0 },
    { $limit: 500}
    ]);

我遵循了java的结构。

AggregateIterable<Document> output=mongoCollection.aggregate(Arrays.asList(...));

1 个答案:

答案 0 :(得分:2)

静态导入辅助类的所有方法,并使用下面的代码。

import static com.mongodb.client.model.Accumulators.*;
import static com.mongodb.client.model.Aggregates.*;
import static java.util.Arrays.asList;
import static com.mongodb.client.model.Sorts.*;
import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Projections.*;

Bson match = match(and(gte("stId", 1), lte("stId", 410)));
Bson sort = sort(descending("objId"));
Bson group = group("$objId", first("maxstId", "$stId"), first("idVal", "$_id"));
Bson projection = project(fields(include("idVal", "maxstId"), excludeId()));
Bson skip = skip(0);
Bson limit = limit(500);
AggregateIterable<Document> output = mongoCollection.aggregate(asList( match, sort, group, projection, skip, limit ));