问题描述
我有两个名为 School 和 Students
的集合学校收藏
{
_id: ObjectId("60008e81d186a82fdc4ff2b7"),name: String,branch: String,class: [{
"active" : true,"_id" : ObjectId("6001e6871d985e477b61b43f"),"name" : "I","order" : 1
},{
"active" : true,"_id" : ObjectId("6001e68f1d985e477b61b444"),"name" : "II","order" : 2
}]
}
学生合集
{
_id: ObjectId("6002def815eccd53a596f830"),schoolId: ObjectId("60008e81d186a82fdc4ff2b7"),sessionId: ObjectId("60008e81d186a82fdc4ff2b9"),class: ObjectId("6001e6871d985e477b61b43f"),}
我想在单次查询中获取Student Collection的数据。
我将类 id
存储在学生集合中,而针对该 id
的数据存储在类键下的学校集合中,该类是对象数组。
你能帮我用这个 id 获取学生集合中的类对象吗?
我想要的输出:
data: {
_id: ObjectId("6002def815eccd53a596f830"),classData: [{
"active" : true,"order" : 1
}]
}
所以我尝试了这个,但没有用:
const students = await this.studentModel.aggregate([
{
$lookup: {
from: 'School',let: { classId: '$class' },pipeline: [
{
$match: {
$expr: { $eq: ['$$classId','$class._id'] },},],as: 'classData',]);
解决方法
-
$lookup
,在schoolId
中传递class
和let
, -
$match
学校 id 条件 -
$filter
迭代class
的循环并过滤特定的类对象 -
$arrayElemAt
将从$filter
的返回结果中获取对象 -
$replaceRoot
将对象替换为 root
const students = await this.studentModel.aggregate([
{
$lookup: {
from: "School",let: {
schoolId: "$schoolId",classId: "$class"
},pipeline: [
{ $match: { $expr: { $eq: ["$$schoolId","$_id"] } } },{
$replaceRoot: {
newRoot: {
$arrayElemAt: [
{
$filter: {
input: "$class",cond: { $eq: ["$$this._id","$$classId"] }
}
},0
]
}
}
}
],as: "classData"
}
}
])