"带有'管道'的$lookup可能不指定'localField'或'foreignField'"



我是猫鼬的新手&mongoDB,我有下面的查询,当运行时抛出follow错误。如果有人能帮助我处理这个问题,并且仍然得到相同的输出,那就太好了

//interview.model.js => mongodb show name as interview
module.exports = mongoose.model('Interview', interviewSchema);
//candidate.model.js => mongodb show name as candidate
module.exports = mongoose.model('Candidate', candidateSchema);
const [result, err] = await of(Interview.aggregate([
{
$match: {
...filterQuery,
}
},
{
$lookup: {
'from': 'candidates',
'localField': 'candidateId',
'foreignField': '_id',
'as': 'candidateId',
pipeline: [
{ $match: { 'candidateId.interviewCount': 0 }},
{ $project: { firstName:1, status:1, avatar:1 } }
]
}
},
]))

MongoDB 4.4或更低版本:

您可以从1(localField/ForeignField或2(使用管道查找使用$lookup的任何一种语法

  • let要声明变量candidateId,可以在pipeline中使用此id,即localField
  • pipeline推送表达式使用$expr$eq匹配,因为我们正在匹配内部字段
  • $$引用将允许在声明为let的管道中使用变量
const [result, err] = await of(Interview.aggregate([
{ $match: { ...filterQuery } },
{ 
$lookup: {
'from': 'candidates',
'as': 'candidateId',
'let': { candidateId: "$candidateId" },
'pipeline': [
{ 
$match: { 
$expr: { $eq: ["$$candidateId", "$_id"] },
'candidateId.interviewCount': 0
} 
},
{ $project: { firstName:1, status:1, avatar:1 } }
]
}
}
]))

MongoDB 5.0或更高版本:

您的查询按照mongodb的最新版本看起来不错,您可以将您的mongodb版本升级到mongodb最新版本。

相关内容

最新更新