嘿,我对猫鼬很陌生,我的头也找不到。
模型
User->resumes[]->employments[]
UserSchema
{
resumes: [ResumeSchema],
...
}
ResumeSchema
{
employments: [EmploymentSchema],
...
}
EmploymentSchema
{
jobTitle: {
type: String,
required: [true, "Job title is required."]
},
...
}
背景
用户必须从现有简历的现有数据中输入职位名称和需求建议,并输入他们的职务名称。
我试过以下代码。
let q = req.query.q; // Software
User.find({ "resumes.employments.jobTitle": new RegExp(req.query.q, 'ig') }, {
"resumes.employments.$": 1
}, (err, docs) => {
res.json(docs);
})
输出
[
{
_id: '...',
resumes:[
{
employments: [
{
jobTitle: 'Software Developer',
...
},
...
]
},
...
]
},
...
]
预期OutPut
["Software Developer", "Software Engineer", "Software Manager"]
Problem 1:)返回的数据太多,因为我只需要jobTitle
2:)所有的工作都已返回,而查询与其中的一项相匹配
3)有什么更好的方法吗?通过索引还是通过$search?我在猫鼬文档中找不到太多信息来创建搜索索引(我也不知道如何创建复合索引以使其工作)
我知道可能有很多答案,但没有人帮上忙,或者我无法让他们发挥作用.我对mongodb非常陌生,我一直通过SQL或ORM处理关系数据库,所以我的mongodb概念和知识是有限的。
因此,如果有更好的解决办法,请告诉我。或者能让现在的那个起作用的东西。
发布于 2021-09-07 21:42:29
您可以使用下面的一个聚合查询来获得这个结果:
[
{
"jobTitle": [
"Software Engineer",
"Software Manager",
"Software Developer"
]
}
]
查询是:
$unwind
两次解构数组并获取值。$match
按您希望使用$regex
筛选的值进行筛选。$group
将所有值集合在一起(使用_id: null
和$addToSet
不添加重复项)。$project
只显示您想要的字段。User.aggregate({
"$unwind": "$resumes"
},
{
"$unwind": "$resumes.employments"
},
{
"$match": {
"resumes.employments.jobTitle": {
"$regex": "software",
"$options": "i"
}
}
},
{
"$group": {
"_id": null,
"jobTitle": {
"$addToSet": "$resumes.employments.jobTitle"
}
}
},
{
"$project": {
"_id": 0
}
})
示例这里
另一种选择是将$filter
应用于$project
阶段:
与以前类似,但两次使用$filter
而不是$unwind
。
User.aggregate({
"$unwind": "$resumes"
},
{
"$project": {
"jobs": {
"$filter": {
"input": "$resumes.employments",
"as": "e",
"cond": {
"$regexMatch": {
"input": "$$e.jobTitle",
"regex": "Software",
"options": "i"
}
}
}
}
}
},
{
"$unwind": "$jobs"
},
{
"$group": {
"_id": null,
"jobTitle": {
"$addToSet": "$jobs.jobTitle"
}
}
},
{
"$project": {
"_id": 0
}
})
示例这里
https://stackoverflow.com/questions/69094158
复制相似问题