我的Cosmos DB中有以下文档 struct (使用mongo查询语言):
Child:
{
id: doc_123_2
parent_id: 123
active: true
}
Parent:
{
_id: doc_123
parent_id: 123
active: true
parent_desc: sample parent desc
}
在下面的代码中,我试图返回所有与其相关的子文档中的"parent_desc"字段-但是我无法让它填充到子文档中,我做错了什么?
我可以在我的投影方法中手动硬编码该字段,但这不是我想要的-我希望它从父文档中提取.
我想我下面代码中的addFieldsStage
似乎没有做任何事情?
private List<Bson> createQuery() {
List<Bson> pipeline = new ArrayList<>();
Bson lookupStage = Aggregates.lookup(
"myCollection",
"parent_id",
"parent_id",
"children"
);
pipeline.add(lookupStage);
// adding parent_desc from parent docs into children?
Bson addFieldsStage = Aggregates.addFields(
new Field<>("parent_desc", "$ROOT.parent_desc")
);
pipeline.add(addFieldsStage);
pipeline.add(Aggregates.unwind("$children"));
pipeline.add(Aggregates.replaceWith("$children"));
pipeline.add(projectFields());
return pipeline;
}
private Bson projectFields() {
return Aggregates.project(new Document()
.append("_id", new Document("$cond", Arrays.asList(
new Document("$ne", Arrays.asList("$_id", null)),
"$_id",
"$$REMOVE"
)))
.append("parentDesc", new Document("$cond", Arrays.asList(
new Document("$ne", Arrays.asList("$parent_desc", null)),
"$parent_desc",
"$$REMOVE"
)))
//... project other fields (working as expected)
}
Note - this question为我提供了当我将其作为mongo查询运行时想要的原始结果.