我正在进行一项大学项目,需要使用ObjectIds填充对象数组,但是我不能在我的项目中使用mongoose。我有两个集合 - subject和studyProgram。
studyProgram文档示例:
{
_id: ObjectId('111'),
name: "Study program 1"
description: "Lorem ipsum dolor sit amet",
language: "en",
subjects: [
{
id: ObjectId('222'),
optionality: "selective",
credits: 8,
},
{
id: ObjectId('333'),
optionality: "selective",
credits: 5
},
],
}
示例 主题 文档:
{
_id: ObjectId('222'),
name: "Subject A",
description: "Subject A description.",
},
{
_id: ObjectId('333'),
name: "Subject B",
description: "Subject B description.",
}
我需要根据id
,将subject集合中的适当文档填充到subjects
数组中。基本上,我想要的结果是这样的:
{
_id: ObjectId('111'),
name: "Study program 1"
description: "Lorem ipsum dolor sit amet",
language: "en",
subjects: [
{
_id: ObjectId('222'),
name: "Subject A",
description: "Subject A description.",
optionality: "selective",
credits: 8,
},
{
_id: ObjectId('333'),
name: "Subject B",
description: "Subject B description.",
optionality: "selective",
credits: 5
},
],
}
到目前为止,我尝试使用了以下 $lookup :
{
$lookup: {
from: "subject",
localField: "subjects.id",
foreignField: "_id",
as: "subjects",
}
}
但这会移除 optionality
和 credits
属性。有没有一种方法可以在不使用 mongoose 的情况下实现这一点?谢谢。
"$first"
只在那个版本的"$group"
中可用。我通过使用"$arrayElemAt"
更新了聚合管道。请查看更新后的答案。 - rickhg12hs