gpt4 book ai didi

mongodb - slice 元素的查找`from`集合上的match字段不起作用

转载 作者:行者123 更新时间:2023-12-01 22:20:49 26 4
gpt4 key购买 nike

我使用gogo作为mongodb的后端使用golang
我的mongodb集合是

employee
{
_id:ObjectId(),
"emp_name":"qwert",
"emp_id":111,
"emp_dept":"XYZ"
"qualification":"PHD",
"employee_status":"working"
}
{
_id:ObjectId(),
"emp_name":"asdfg",
"emp_id":121,
"emp_dept":"XYZ"
"qualification":"MBA"
"employee_status":"working"
}
department{
_id:ObjectId(),
"dept_id":11,
"dept_name":"XYZ",
"description":"decs",
"department_status":"active"
}
我的Go代码是
 type DepartmentInfo struct {
DepartmentID int `json:"dept_id" bson:"dept_id"`
DepartmentName string `json:"dept_name" bson:"dept_name"`
Description string `json:"description" bson:"description"`
EmployeeList []EmployeeInfo `json:"employee_list" bson:"employee_list"`
}
type EmployeeInfo struct {
EmployeeID int `json:"emp_id" bson:"emp_id"`
EmployeeName string `json:"emp_name" bson:"emp_name"`
Qualification string `json:"qualification" bson:"qualification"`
Dept_Name string `json:"emp_dept" bson:"emp_dept"`
Address string `json:"address" bson:"address"`
}

collection := session.DB("db").C("department")
pipeline := collection.Pipe([]bson.M{
{"$match": bson.M{ "dept_id": 104, }},
{"$lookup": bson.M{
"from": "employee",
"localField": "dept_name",
"foreignField": "emp_dept",
"as": "employee_list",
}},
{"$match": bson.M{ "employee_list.qualification": "PHD", }},
})
var departmentInfo Department
err = pipeline.One(&departmentInfo)
它会返回部门信息以及所有员工的名单,而不匹配其资格。那么如何对集合中 slice返回的 lookup应用匹配运算符?

最佳答案

您可以将$filter用作$project$addFields阶段的一部分,而不是在最后一个阶段使用$ match。
因此,您的管道如下所示:

[{
$match: {
dept_id: '11'
}
}, {
$lookup: {
from: 'employee',
localField: 'dept_name',
foreignField: 'emp_dept',
as: 'employee_list'
}
}, {
$project: {
dept_id: 1,
dept_name: 1,
description: 1,
employeesWithPHD: {
$filter: {
input: '$employee_list',
as: 'employee',
cond: {
$and: [{
$eq: [
'$$employee.qualification',
'PHD'
]
},
{
$eq: [
'$$employee.employee_status',
'working'
]
}
]
}
}
}
}
}]

关于mongodb - slice 元素的查找`from`集合上的match字段不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63615987/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com