Mongo DB Bson 和 Java:在子文档中添加和返回仅存在于父文档中的字段?

问题描述 投票:0回答:1

我的 Cosmos DB 中有以下文档结构(使用 mongo 查询语言):

孩子:

    {
    id: doc_123_2
    parent_id: 123
    active: true
}

家长:

{
_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)
            }

注意 - 这个问题 当我将其作为 mongo 查询运行时,它给了我想要的原始结果。

java spring mongodb nosql projection
1个回答
0
投票

$addFields
阶段应该看起来像
{"children.parent_desc": "$parent_desc"}
所以查询变成这样。在 Java 代码中看起来像
  Bson addFieldsStage = Aggregates.addFields( new Field<>("children.parent_desc", "$parent_desc") );

db.myCollection.aggregate([
  {
    $lookup: {
      from: "myCollection",
      localField: "parent_id",
      foreignField: "parent_id",
      as: "children"
    }
  },
  {
    $addFields: {
      "children.parent_desc": "$parent_desc"
    }
  },
  {
    $unwind: "$children"
  },
  {
    $replaceWith: "$children"
  }
])

游乐场

© www.soinside.com 2019 - 2024. All rights reserved.