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",
}
My Go Code is
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)
It shows Department Details with Employee Slice empty
I want to get deartment info of 'XYZ' dept with list of all employees working inside that department. I have uploaded my collections and struct as Example
Your Department
struct has a EmployeeList []Employee
field, so if you plan to unmarshal the aggregation result into Department
values, you have to remove the $unwind
stage.
Something like this should work:
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)
Also you have a EmployeeDept String
field in Employee
, I don't know what your String
type is, maybe it's just string
?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.