【发布时间】:2021-04-21 17:26:05
【问题描述】:
我有一个需要按年份分组的集合。我的聚合管道是这样的:
const WorkHistoryByYear = await this.workHistroyModel.aggregate([
{
$group: {
_id: '$year',
history: {
$push: '$$ROOT'
}
}
}
]);
按预期工作,返回:
[{
"_id": 2003,
"history": [
{
"_id": "600331b3d84ac418877a0e5a",
"tasksPerformed": [
"5fffb180a477c4f78ad67331",
"5fffb18aa477c4f78ad67332"
],
"year": 2003
},
{
"_id": "600331dcd84ac418877a0e5c",
"tasksPerformed": [
"5fffb180a477c4f78ad67331"
],
"year": 2003
}
]
}]
但如果可能,我想填充一个字段。
WorkHistory 架构有一个字段 tasksPerformed,它是 ObjectId 引用的数组。这是Task 架构:
export const TaskSchema = new Schema({
active: {
type: Schema.Types.Boolean,
default: true,
},
title: {
type: Schema.Types.String,
required: true,
},
order: {
type: Schema.Types.Number,
index: true,
}
});
是否可以在聚合中填充引用的模型? $lookup 似乎是我所需要的,但在遵循文档时我还没有让它工作。
我没有做很多数据库工作,所以我很难找到合适的运算符来使用,我也看到过类似的问题,但没有明确的答案。
编辑:
从@varman 的回答中添加代码后,我现在的回报是:
{
"_id": 2003,
"history": {
"_id": "600331b3d84ac418877a0e5a",
"tasksPerformed": [
"5fffb180a477c4f78ad67331",
"5fffb18aa477c4f78ad67332"
],
"year": 2003,
"history": {
"tasksPerformed": []
}
}
}
为了帮助匹配,我将 ObjectId 引用转换为字符串,但我仍然做得不够。
【问题讨论】:
-
你能发布一些示例数据吗
-
@varman 我添加了聚合数据的精简示例
-
模型内的人口是可能的,你所说的
$lookup也是正确的。我们还有其他你需要加入的收藏吗? -
@varman 我已经为相关的“任务”模型添加了架构
-
TaskSchema有工作历史的参考吗?