如何使用 go 和 mongodb 获取在另一个结构中定义的类型结构的切片

how to get slice of type struct defined inside another struct using go and mongodb

mongodb collections

employee
{
  _id:ObjectId(),
  "emp_name":"qwert",
  "emp_id":111,
  "emp_dept":"XYZ"
}
{
_id:ObjectId(),
  "emp_name":"asdfg",
  "emp_id":121,
  "emp_dept":"XYZ"
}
department{
_id:ObjectId(),
"dept_id":11,
"dept_name":"XYZ",
"description":"decs",
}

我的围棋代码是

 type Employee struct {
    EmployeeName  string             `json:"emp_name" bson:"emp_name"`
    EmployeeID    int                `json:"emp_id" bson:"emp_id"`
    EmployeeDept  String             `json:"emp_dept" bson:"emp_dept"`
    EmpDepartment Department         `json:"department" bson:"department"` 
}
 type Department struct {
    DepartmentID    int                `json:"dept_id" bson:"dept_id"`
    DepartmentName  string             `json:"dept_name" bson:"dept_name"` 
    Description     string             `json:"description" bson:"description"` 
    EmployeeList    []Employee         `json:"employee_list" bson:"employee_list"`
}

collection := session.DB("db").C("department")
pipeline := collection.Pipe([]bson.M{
        {"$match": bson.M{
        "dept_name": "xyz",
          }},
        {"$lookup": bson.M{
        "from":         "employee",
        "localField":   "dept_name",
        "foreignField": "emp_dept",
        "as":           "employee_list",
    }},
        {"$unwind": "$employee_list"},
    })

err = pipeline.One(&departmentEmployees)

它显示员工切片为空的部门详细信息

我想获取 'XYZ' 部门的部门信息以及在该部门工作的所有员工的列表。 我已经上传了我的 collections 和结构作为示例

您的 Department 结构有一个 EmployeeList []Employee 字段,因此如果您计划将聚合结果解组为 Department 值,则必须删除 $unwind 阶段。

像这样的东西应该可以工作:

collection := session.DB("db").C("department")
pipeline := collection.Pipe([]bson.M{
    {"$match": bson.M{
        "dept_name": "xyz",
    }},
    {"$lookup": bson.M{
        "from":         "employee",
        "localField":   "dept_name",
        "foreignField": "emp_dept",
        "as":           "employee_list",
    }},
})

var departments []*Department
err = pipeline.One(&departments)

你在Employee中还有一个EmployeeDept String字段,我不知道你的String类型是什么,也许只是string