CuteBoy
CuteBoy

Reputation: 99

How to perform aggregation in mongodb using Java by setting query object instead of matchoperation?

Below is the code:

            Criteria criteria=null;
            criteria = new Criteria().andOperator(Criteria.where("OwnerId").is(ownerId), Criteria.where("Environment").is(env), Criteria.where("ServiceName").in(api));
            MatchOperation matchOp= Aggregation.match(criteria);
            ProjectionOperation projOp= Aggregation.project("SubServices").andInclude("ServerGroupName").andInclude("NodeName").andInclude("ServiceVersion")
                    .andExclude("_id");
            Aggregation aggr = Aggregation.newAggregation(matchOp, projOp);
            AggregationResults<Document> aggregate = mongoOperations.aggregate(aggr, "CNF_SERVICE",Document.class,"config",env);

The above code works fine. However, I need to make below changes in order to generate criteria dynamically:

            Criteria criteria=new Criteria();
            Query query= new Query();
            if(ownerId!=null && ownerId>0) {
                query.addCriteria(criteria.andOperator(Criteria.where("OwnerId").is(ownerId)));
            }
            if(env!=null) {
                query.addCriteria(criteria.andOperator(Criteria.where("Environment").is(env)));
            }
            if(api!=null) {
                query.addCriteria(criteria.andOperator(Criteria.where("ServiceName").in(api)));
            }
            MatchOperation matchOp= Aggregation.match("How to set the query here?");
            ProjectionOperation projOp= Aggregation.project("SubServices").andInclude("ServerGroupName").andInclude("NodeName").andInclude("ServiceVersion")
                    .andExclude("_id");
            Aggregation aggr = Aggregation.newAggregation(matchOp, projOp);
            AggregationResults<Document> aggregate = mongoOperations.aggregate(aggr, "CNF_SERVICE",Document.class,"config",env);

I need to set the query to criteria and apply it to the match operation. How to achieve this?

Upvotes: 2

Views: 486

Answers (1)

Ajeeth
Ajeeth

Reputation: 46

Instead of Match Operation you can achieve like below code: Hope, it will helpful

Criteria criteria=new Criteria(); Query query= new Query(); query.addCriteria(criteria.andOperator(Criteria.where("OwnerId").is(ownerId))); query.fields().include("SubServices"); query.fields().include("ServerGroupName"); query.fields().exclude("_id"); MongoTemplate.find(query, Map.Class, collectionName);

Upvotes: 1

Related Questions