Home > Enterprise >  mongodb aggregation-framework, $lookup should only return a specific property instead of whole objec
mongodb aggregation-framework, $lookup should only return a specific property instead of whole objec

Time:01-10

so i've been trying to get get a specific field of $lookup result, i start with this:

$lookup: {
  from : "answers",
  localField: "_id",
  foreignField: "questionID",
  as: "usersAnswered"
} 

it returns something like this:

{
        _id: "616974f1b4f67d0220fe2cf1",
        questionText: "text abc ?",
        userID: "614c7a75403a5636b4029f28",
        usersAnswered: [{
          _id: "6169635cb4f67d0220fe2aa4",
          answerText: "xyz",
          questionID: "616974f1b4f67d0220fe2cf1",
          userID: "614c7a75403a5636b4029f21"
        },{
          _id: "6169635cb4f67d0220fe2ab8",
          answerText: "lmo",
          questionID: "616974f1b4f67d0220fe2cf1",
          userID: "614c7a75403a5636b4029cc2"
        }]
      }

in this example what i'm trying to achieve is get only userID from usersAnswered array instead if whole object which i really don't need. it should look like:

usersAnswered: [{
          userID: "614c7a75403a5636b4029f21"
        },{
          userID: "614c7a75403a5636b4029cc2"
        }]
      }

I've actually tried to get it done but i wasn't able to accomplish it so had to get some help, could i perhaps do something like

$lookup: {
  from : "answers",
  localField: "_id",
  foreignField: "questionID.userID",
  as: "usersAnswered"
} 

or maybe the key is to $group after $unwind since i'm really new to aggregation framework i wasn't able to see it through please go easy on me since i'm really new to this.

CodePudding user response:

If you run already MongoDB 5.0 then try this one:

{
   $lookup:
      {
         from: "answers",
         localField: "_id",
         foreignField: "questionID",
         pipeline: [ {$project: {userID: 1} } ],
         as: "usersAnswered"
      }
}

Otherwise add this stage after $lookup:

{ $set: 
   { 
      usersAnswered: { 
         $map: { input: "$usersAnswered", in: { userID: "$$this.userID" } } 
      } 
   } 
}
  •  Tags:  
  • Related