汇总以合并收集尝试

时间:2019-08-14 16:15:50

标签: java mongodb join

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

1 个答案:

答案 0 :(得分:0)

问题:

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