如何在 Spring 中编写以下 mongoDB 查询?
db.reportData.aggregate([
{ $match : { iecode : {$in:["P110017","P111111"]} } } ,
{
"$group": {
"_id": "$iecode",
"treatmentArms": { "$first": "$evaluationDTOList" }
}
},
{ "$unwind": "$treatmentArms" },
{
"$group": {
"_id": null,
"Package": {
"$sum": {
"$cond": [
{ "$eq": [ "$treatmentArms.mechanismOrPkg", "Package" ] },
1, 0
]
}
},
"Behavioral-bias related mechanisms":{
"$sum": {
"$cond": [
{
"$and": [
{ "$eq": [ "$treatmentArms.mechanismOrPkg", "Mechanism" ] },
{ "$eq": [ "$treatmentArms.mechanismTested1", "Behavioral-bias related mechanisms" ] }
]
},
1,
0 ]
}
}
}
}
])
我的数据库名称:MyProjects 集合名称:reportData
请注意,我使用的是 spring MongoTemplate。
编辑
这是我尝试过的代码
@SuppressWarnings("deprecation")
public void getIEQuestions(Map<String, List<String>> paramMap){
System.out.println("get ie questions-------------------------------------------");
DBCollection projects = getMongoOperations().getCollection("reportData");
BasicDBObject andQuery = new BasicDBObject();
List<BasicDBObject> filters = new ArrayList<BasicDBObject>();
for (Map.Entry<String, List<String>> entry : paramMap.entrySet()) {
ArrayList<String> vals = new ArrayList<String>();
boolean flag = false;
for (int i = 0; i < entry.getValue().size(); i++) {
if (entry.getValue().get(i) != null && entry.getValue().get(i) != "") {
System.out.println("entry.getValue().get(i): " + entry.getValue().get(i));
vals.add(entry.getValue().get(i));
flag = true;
}
}
if (flag) {
filters.add(new BasicDBObject(entry.getKey(), new BasicDBObject("$in", vals)));
}
}
andQuery.put("$and", filters);
//adding all the filters I want to apply
DBObject match = new BasicDBObject("$match", andQuery);
DBObject groupByIECode = new BasicDBObject("$group",
new BasicDBObject("_id","$iecode"))
.append("treatmentArms",new BasicDBObject("$first","$evaluationDTOList"));
DBObject unwind = new BasicDBObject("$unwind","$treatmentArms");
DBObject finalCalculation = new BasicDBObject("$group",new BasicDBObject("_id",null))
.append(
"Package", new BasicDBObject(
"$sum", new BasicDBObject(
"$cond", new Object[]{
new BasicDBObject(
"$eq", new Object[]{ "$treatmentArms.mechanismOrPkg", "Package"}
),
1,
0
}
)
)
);
final AggregationOutput output = projects.aggregate(match, groupByIECode, unwind, finalCalculation);
for (DBObject result1 : output.results()) {
String totalPackage = (String) result1.get("Package");
System.out.println("Total package: "+totalPackage);
}
}
它给了我 duplicateMongoKey 异常。
后来我从这里$cond
发现spring mongotemplate还不支持操作