I'm doing a $lookup from a _id. So the result is always 1 document. Hence, I want the result to be an object instead an array with one item.
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]" } } ]);
This notation: "$typeCategory[0]"
is not working. Is there any smart way of doing this?
You can just use $unwind
. It deconstructs an array field from the input documents to output a document for each element
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" } } ]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With