根据仅存在于父级中的字段查询子文档?

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

在我的 MongoDB 集合中,我有一个遵循父子结构的文档。

每个父文档通常有 4 个字段,子文档有 3 个(无组字段)。

家长:

{
_id: doc_123
parent_id: 123
active: true
group: A
}

孩子们

{
id: doc_123_1
parent_id: 123
active: true
}

{
id: doc_123_2
parent_id: 123
active: true
}

如果我的 Java Spring 项目需要,我想编写一个 BSON 查询/聚合,它将返回与用户提供的以下字段匹配的所有文档:

  • 活动字段 - 这将是 true 或 false
  • 组字段 - 例如“A”

我的困难在于,假设每个子文档与组字段的父文档具有相同的值,但它实际上并不在文档中。

如何编写一个查询来匹配某个组的所有父文档和子文档?

所有文档都在一个集合中,父文档和子文档没有单独的集合。

java json mongodb bson
1个回答
0
投票

聚合步骤:

  1. 根据用户提供的值按
    group
    active
    true/false 进行搜索。
    • 请注意,只有父记录有该组,子组缺失/为空
    • 所以这个阶段只返回匹配的父母
  2. 使用
    parent_id
    自查找同一集合并在
    parent_id
    上进行匹配
    • 无论出于何种原因,
      parent_id
      对于孩子和父母来说是相同的。
    • 小孩子的
      id
      id
      还是
      _id
      ?但不影响这里的管道。
  3. 如果您只需要子记录,请排除父记录。请参阅该阶段的评论。
db.collection.aggregate([
  {
    $match: {
      // set this to a variable for true/false search
      active: true,
      // set this to a variable for group search
      // only "parents" have the group
      group: "A"
    }
  },
  {
    // self-lookup into the same collection, matching on parent_id
    $lookup: {
      from: "collection",
      localField: "parent_id",
      foreignField: "parent_id",
      as: "children"
    }
  },
  { $unwind: "$children" },
  { $replaceWith: "$children" },
  {
    // exclude the parents
    // IF YOU WANT PARENTS ALSO THEN REMOVE THIS STAGE
    $match: {
      group: { $exists: false }
    }
  }
])

蒙戈游乐场

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