代码如下:
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);
我需要将查询设置为条件并将其应用于匹配操作。如何做到这一点?
1条答案
按热度按时间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);