Reputation: 891
I have below aggregation query. Am new to mongo world. Can someone help me translate this into equivalent JAVA query.
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}
]);
I have follow struture for java.
AggregateIterable<Document> output=mongoCollection.aggregate(Arrays.asList(...));
Upvotes: 0
Views: 737
Reputation: 75914
Statically import all the methods of helper classes and use the below code.
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 ));
Upvotes: 2