//根据单位ID,递归查询所有子单位
db.getCollection("Sys_RT_Unit").aggregate([
  {
    $match: {
      UNIT_CODE: "912bb6b5997646f6b6e88a771e1db3bf" // 这里替换为你要查询的父单位ID
    }
  },
  {
    $graphLookup: {
      from: "Sys_RT_Unit",
      startWith: "$UNIT_CODE",
      connectFromField: "UNIT_CODE",
      connectToField: "SUPERIOR_UNIT_CODE",
      as: "hierarchy"
    }
  },
    
    {
    $project: {
            result: { 
                $concatArrays: ['$hierarchy', []]
            }
        }
  },
    {
    $unwind: "$result"
  },
    {
    $replaceRoot: {
            newRoot: "$result"
        }
  }
    
]);

//connectFromField和connectToField字段指定了父子关系字段,as字段指定了结果输出的字段名称。
//replaceRoot:将子对象转为根对象
//unwind:将孩子数组的N个对象解开为N条对象(独立出来)
//concatArrays:多个数组合并在同一个数组里

 

 posted on 2024-06-26 11:42  布鲁布鲁sky  阅读(2)  评论(0编辑  收藏  举报