首页 > 解决方案 > 聚合以组合集合尝试

问题描述

我想在 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"));

标签: javamongodbjoin

解决方案


问题:

  • 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());
}

推荐阅读