2017-04-27 180 views
0

我有下面的聚合查詢。我對mongo世界很陌生。有人可以幫我翻譯成等效的JAVA查詢。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(...)); 

回答

2

靜態導入helper類的所有方法並使用下面的代碼。

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)); 
+0

我發佈後,我能夠使用github上的文件進行轉換....感謝反正:) – ProgrammerBoy