Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert a $lookup result to an object instead of array

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?

like image 288
Joe Avatar asked Jan 11 '17 23:01

Joe


1 Answers

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"       }     }   ]); 
like image 80
sidgate Avatar answered Sep 21 '22 17:09

sidgate