我正在使用最新的库更新 2014 Java 项目,MongoDB Java 驱动程序从 3.0 更改为 3.6。大多数代码已经更新,但有一个非常复杂的特定查询给我带来了问题。
文档是这样的
{
"_id" : ObjectId("58750a67ae28bc28e0705b0f"),
"info": "description",
"parentId", "variable-id-here"
"issues": [
{"name": "a", "closed": true},
{"name": "b", "closed": false},
{"name": "c", "closed": true}
],
"bugs": [
{"name": "d", "closed": false},
{"name": "e", "closed": false},
{"name": "f", "closed": true}
],
"errors": [
{"name": "g", "closed": true},
{"name": "h", "closed": true},
{"name": "i", "closed": false}
]
}
(即使数组中的元素相似,也不能将它们分组到文档中的单个数组中,并使用带有值 [问题、错误、错误] 的额外“类型”键,但这不是重点)
旧脚本是这个
List<DBObject> aggregators = new ArrayList<>();
DBObject match = new BasicDBObject("$match", new BasicDBObject("parentId", myId));
DBObject project = new BasicDBObject();
List<String> domains = Arrays.asList("issues", "bugs", "errors");
for (Iterator<String> d = domains.iterator(); d.hasNext();) {
String domain = d.next();
//Reset values
aggregators = new ArrayList<>();
// Define MongoDB "$project" to find 'true' values on 'closed' flags
project = new BasicDBObject("$project", new BasicDBObject("closedProblems",
new BasicDBObject("$filter",
new BasicDBObject("input", "$"+domain)
.append("as", "myObject")
.append("cond", new BasicDBObject("$eq",
Arrays.<Object> asList("$$myObject.closed", true)
)
)
)
));
aggregators.add(match);
aggregators.add(project);
//db defined before. AggregationOutput is deprecated so must be changed
AggregationOutput output = db.getCollection("myColl").aggregate(aggregators);
// Now I can iterate results
for (DBObject result : output.results()) {
// ...
}
}
我尝试使用项目、表达式等,但找不到使用新聚合方法复制 MongoDB 项目的方法。
最终结果应该使用mongoTemplate。anyMethods为了加入新的项目指南来执行聚合
相关分类