感谢来到我的岗位。我是MongoDB的新手,我需要帮助。我需要从数据库中选择用户数据,所以我有一个非常简单的管道:
const pipeline = [{
$match: {
type: 'student',
counselorUserName: username
},
$project: {
username: '$username',
email: '$email',
phone: '$phone',
fullName: '$fullName',
gradeLevel: {
$switch: {
branches: [{
case: {
$eq: ['$gradeLevel', '9']
},
then: 'Freshman'
},
{
case: {
$eq: ['$gradeLevel', '10']
},
then: 'Sophomore'
},
],
default: "Freshman"
}
}
},
$lookup: {
from: 'RoadmapTasksCompleted',
let: {
username: '$username',
gradeLevel: '$gradeLevel'
},
pipeline: [
{
$match: {
monthToComplete: {
$in: prevMonthsNames
},
$expr: {
$and: [
{
$eq: ['$username', '$$username']
},
{
$eq: ['$gradeLevel', '$$gradeLevel']
}
]
}
}
},
{
$group: {
_id: null,
count: { $sum: 1 }
}
}
],
as: 'completedTasksCount'
}
}
工作正常,我得到:
{
username: "hewy",
email: "htheodros@usfca.edu",
phone: "4049159553",
fullName: "Hewotte Theodros",…}
completedTasksCount:[{_id: null, count: 27}]
}
但是我需要在查找下面添加新的阶段,当我这样做时,completedTasksCount
变成空数组[]
,为什么会发生这种情况以及如何解决呢?
我需要添加以下阶段:
$project: {
username: '$username',
email: '$email',
phone: '$phone',
fullName: '$fullName',
completedTasks: { $arrayElemAt: ['$completedTasksCount', 0] },
tasksCountMap: tasksCountArray
},
$addFields: {
status: {
$let: {
vars: {
tasksCount: {
$arrayElemAt: [
"$tasksCountMap.v",
{
$indexOfArray: ["$tasksCountMap.k", "$gradeLevel"]
}
]
},
completedTasksCount: '$completedTasks.count'
},
in: {
$cond: {
if: { $or: [
{ $eq: ['$$tasksCount', '$$completedTasksCount'] },
{ $lte: ['$$tasksCount', '$$completedTasksCount'] },
]},
then: 'On track',
else: 'High priority'
}
}
}
}
},
感谢帮助。