java - 聚合以组合集合尝试
问题描述
我想在 Java 中执行聚合:这是我的尝试
部门收集的示例。
{
"_id" : ObjectId("5d4dc8635dd32dbcba4ae0ae"),
"name" : "Sales"
}
employee_dept 集合的示例
{
"_id" : ObjectId("5d5411be6cd7524f36a7933f"),
"dept_id" : ObjectId("5d4dc8635dd32dbcba4ae0ae"),
"employee_id" : ObjectId("5d4dc8635dd32dbcba4ae0af")
}
预期输出示例
{
"_id" :"5d4dc8635dd32dbcba4ae0ae",
"name" : "Sales"
}
Java 代码
DBObject match = new BasicDBObject("$match", new BasicDBObject("employee_id", "5d4dc8635dd32dbcba4ae0af"));
// build the $lookup operations
DBObject lookupFields = new BasicDBObject("from", "dept");
lookupFields.put("localField", "dept_id");
lookupFields.put("foreignField", "_id");
lookupFields.put("as", "dept");
DBObject lookup = new BasicDBObject("$lookup", lookupFields);
// build the $projection operations
DBObject projectFields = new BasicDBObject("name", 1);
projectFields.put("_id", 1);
DBObject project = new BasicDBObject("$project", projectFields);
List<DBObject> pipeline = Arrays.asList(match, lookup, project);
AggregateIterable aggregateIterable = dbCollection.aggregate(pipeline);
for(Object result: aggregateIterable) {
System.out.println(result);
}
问题:由于某种原因,aggregateIterable 没有得到输出
B)如果您不介意在以下内容中添加 $employee_dept._id 和 employee_id 的投影方式?
Document project = new Document("$project", new BasicDBObject("name", "$dept.name")
.append("e_id", "$employee_department._id")
.append("employee_id", "$employee_department.employee_id")
.append("dept_id", "$dept._id"));
解决方案
问题:
- ObjectId 类型的employee_id 与字符串的比较
- 在投影中,名称和 _id 在 'dept' 数组中,而不是在根级别
固定代码:
Document match = new Document("$match", new Document("employee_id", new ObjectId("5d4dc8635dd32dbcba4ae0af")));
// build the $lookup operations
Document lookupFields = new Document("from", "dept");
lookupFields.put("localField", "dept_id");
lookupFields.put("foreignField", "_id");
lookupFields.put("as", "dept");
Document lookup = new Document("$lookup", lookupFields);
// build unwind operation
Document unwind = new Document("$unwind", "$dept");
// build the $projection operations
Document projectFields = new Document("name", "$dept.name");
projectFields.put("_id", new Document("$toString", "$dept._id"));
Document project = new Document("$project", projectFields);
List<Document> pipeline = Arrays.asList(match, lookup, unwind, project);
AggregateIterable<Document> aggregateIterable = groupDAO.database.getCollection("employee_dept")
.aggregate(pipeline);
for (Document result : aggregateIterable) {
System.out.println(result.toJson());
}
推荐阅读
- excel - 如何修复 Excel 中包含公式但显示为空单元格的单元格?
- node.js - 如何在nodejs中对这种类型的嵌入式文档数组使用POST请求
- sql - 从最后一组字符之间选择子字符串
- active-directory - Microsoft Graph 是否有任何 api 来更新分配给用户的项目名称?
- speech-to-text - 以 48kHz 采样的 Speech-to-Text 语音训练数据是否仍然有助于提高对 16kHz 语音的识别?
- c++ - Code Chef DSA 学习系列:3 的倍数
- android - 在 Kotlin 中创建中间进度条
- python - 如何设置一个获取灰度图像并输出 ARGB 的图层,使其中一种灰度颜色透明?
- javascript - 在 Ionic4 React 的 onIonChange 上运行两个函数
- javascript - 用户填写结帐表单时使用 Ajax 引发错误消息