我正在从_id进行$ lookup.所以结果总是1个文件.因此,我希望结果是一个对象,而不是一个包含一个项目的数组.
let query = mongoose.model('Discipline').aggregate([ { $match: { project: mongoose.Types.ObjectId(req.params.projectId) }, }, { $lookup: { from: "typecategories", localField: "typeCategory", foreignField: "_id", as: "typeCategory" } }, { $project: { title: 1, typeCategory: "$typeCategory[0]" } } ]);
这种表示法:"$typeCategory[0]"
不起作用.这有什么聪明的方法吗?
你可以使用$unwind
.它从输入文档中解构数组字段,以输出每个元素的文档
let query = mongoose.model('Discipline').aggregate([ { $match: { project: mongoose.Types.ObjectId(req.params.projectId) }, }, { $lookup: { from: "typecategories", localField: "typeCategory", foreignField: "_id", as: "typeCategory" } }, {$unwind: '$typeCategory'}, { $project: { title: 1, typeCategory: "$typeCategory" } } ]);