如何使用java在mongodb中通过设置query object而不是matchoperation进行聚合?

nfs0ujit  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(265)

代码如下:

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

上面的代码工作正常。但是,为了动态生成标准,我需要进行以下更改:

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

我需要将查询设置为条件并将其应用于匹配操作。如何做到这一点?

osh3o9ms

osh3o9ms1#

而不是匹配操作,你可以实现如下代码:希望,这将有帮助
criteria=新标准();query=新建查询();query.addcriteria(criteria.andoperator(criteria.where(“ownerid”).is(ownerid)));query.fields().include(“子服务”);query.fields().include(“servergroupname”);query.fields().exclude(“_id”);mongotemplate.find(query,map.class,collectionname);

相关问题