我的数据库中有两个集合,Projects
和Tasks
。每个项目都可以有许多与之相关的任务。我正在尝试用Java创建一个MongoDB查询,该查询将返回Task
并嵌入与其链接的Project
,但是到目前为止我完成的代码只返回一个空数组(我有将此something
命名为下面的[]
。
不幸的是,我没有找到很多关于如何在Java中正确使用$lookup
的例子。我需要对代码执行哪些更改,以便something
字段返回project
?我应该使用$lookup
还是其他聚合运算符?
我使用的mongo-java-driver版本3.5.0的Java方法:
public static String readTask()
{
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("exampleDatabase");
Bson lookup = new Document("$lookup",
new Document("from", "Project")
.append("localField", "project._id")
.append("foreignField", "_id")
.append("as", "something"));
List<Bson> filters = new ArrayList<>();
filters.add(lookup);
AggregateIterable<Document> it = database.getCollection("Task").aggregate(filters);
System.out.println("First Document: " + it.first().toString());
return it.first().toString();
}
此方法目前返回以下内容:
{
_id = 599a62cac29d9a2684c64012,
constructionRoomNumber = 15,
type = Example,
summary = Summary Text,
description = Description Text,
status = Open,
project = {
"$ref": "Project",
"$id": "5996582a0983347784fb2ff4"
},
something = []
}
预期结果:
{
_id: ObjectId('599a62cac29d9a2684c64012')
constructionRoomNumber: "15"
type: "Example"
summary: "Summary Text"
description: "Description Text"
status: "Open"
project: {
_id: ObjectId('5996582a0983347784fb2ff4')
projectCode: "V1000"
projectName: "Example Project"
projectLocation: "1 Somewhere Street, Some City"
clientName: "Whatever Client"
isActive: true
}
}
以下是MongoDB中存储的数据的示例:
示例项目:
_id: ObjectId('5996582a0983347784fb2ff4')
projectCode: "V1000"
projectName: "Example Project"
projectLocation: "1 Somewhere Street, Some City"
clientName: "Whatever Client"
isActive: true
示例任务:
_id: ObjectId('599a62cac29d9a2684c64012')
constructionRoomNumber: "15"
type: "Example"
summary: "Summary Text"
description: "Description Text"
status: "Open"
project: DBRef(Project, 5996582a0983347784fb2ff4, undefined)
答案 0 :(得分:0)
您正在尝试查找不受支持的DBRef字段。
但是,有一个workaround to transform DBRefs into simple ObjectId that I have detailed on a different answer,你可以用Java调整它或在原生查询中使用它。