gpt4 book ai didi

java - MongoDB $lookup 查询返回空字段

转载 作者:可可西里 更新时间:2023-11-01 10:48:51 26 4
gpt4 key购买 nike

我的数据库中有两个集合,ProjectsTasks。每个项目都可以有许多与之关联的任务。我正在尝试在 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)

最佳答案

您正在尝试查找不受支持的 DBRef 字段。

然而,有一个workaround to transform DBRefs into simple ObjectId that I have detailed on a different answer ,您可以在 Java 中对其进行调整或在 native 查询中使用它。

关于java - MongoDB $lookup 查询返回空字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45806890/

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