gpt4 book ai didi

java - 聚合以合并集合尝试

转载 作者:行者123 更新时间:2023-12-02 01:39:13 24 4
gpt4 key购买 nike

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

关于java - 聚合以合并集合尝试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57498495/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com