我有一个拥有技能的用户数据库。我已经建立了一种方法,使用mongoose中包含的am聚合方法在数据库中查找用户。根据我输入聚合的搜索条件,结果可能太大,无法在我的前端应用程序上实际显示。我很好奇如何使用典型的限制,页面,并像在典型的GET请求中那样跳过变量。
下面是我的聚合查询:
const foundUsers = await User.aggregate([
{
$addFields: {
matchingSkills: {
$filter: {
input: '$skills',
cond: {
$or: test,
},
},
},
requiredSkills,
},
},
{
$addFields: {
// matchingSkills: '$$REMOVE',
percentageMatch: {
$multiply: [
{ $divide: [{ $size: '$matchingSkills' }, skillSearch.length] }, // yu already know how many values you need to pass, thats' why `2`
100,
],
},
},
},
{
$addFields: {
matchingSkillsNames: {
$map: {
input: '$matchingSkills',
as: 'matchingSkill',
in: '$$matchingSkill.skill',
},
},
},
},
{
$addFields: {
missingSkills: {
$filter: {
input: '$requiredSkills',
cond: {
$not: {
$in: ['$$this', '$matchingSkillsNames'],
},
},
},
},
},
},
{
$match: { percentageMatch: { $gte: 25 } },
},
]);
字符串
将这些技能传递给这个聚合函数:
{
"skillSearch": [
{
"class": "skills",
"skill": "SQL",
"operator": "GT",
"yearsExperience": 6
},
{
"class": "skills",
"skill": "C",
"operator": "GT",
"yearsExperience": 1
}
]
}
型
将导致类似于以下的响应:
{
"_id": "60184ce81e65633873d709aa",
"name": "Brad",
"email": "[email protected]",
"password": "$2a$12$37v2RwaO5LhSMT8GJQSZyel.Aawn6AmlqqSOkZtopqIIXyJ0LRBfu",
"__v": 0,
"skills": [
{
"_id": "60a306ce819cde701c1934a8",
"skill": "SQL",
"yearsExperience": 8
},
{
"_id": "60a306ce819cde701c1934a9",
"skill": "C",
"yearsExperience": 5
},
{
"_id": "60a306ce819cde701c1934aa",
"skill": "PL/I",
"yearsExperience": 2
},
{
"_id": "60a306ce819cde701c1934ab",
"skill": "Awk",
"yearsExperience": 9
}
],
"matchingSkills": [
{
"_id": "60a306ce819cde701c1934a8",
"skill": "SQL",
"yearsExperience": 8
},
{
"_id": "60a306ce819cde701c1934a9",
"skill": "C",
"yearsExperience": 5
}
],
"requiredSkills": [
"SQL",
"C"
],
"percentageMatch": 100,
"matchingSkillsNames": [
"SQL",
"C"
],
"missingSkills": []
},
型
2条答案
按热度按时间r8uurelv1#
对于分页,需要从前端传递
page
和size
$sort
对文档进行排序,$skip
跳过文档。例如:如果你在第二页,你需要10行,你需要跳过前10个文档$limit
到跳过后需要显示多少文档这里是代码
字符串
工作Mongo playground
更重要的是,分页也需要全部元素,
型
工作Mongo playground
uemypmqf2#
对于新读者,正如已经回答的那样,您可以轻松地将跳过和限制阶段添加到聚合中。我想添加的是使用easy-mongoose-paginate包来为您解决这个问题https://www.npmjs.com/package/easy-mongoose-paginate#easy-mongoose-paginate
字符串