user14230999
user14230999

Reputation:

$lookup should only return a specific property instead of whole object

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.

Upvotes: 0

Views: 2530

Answers (1)

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59436

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" } } 
      } 
   } 
}

or

{ $set: 
   { 
      usersAnswered: {$first:
         { 
         $map: { input: "$usersAnswered", in: { userID: "$$this.userID" } } 
      }
      } 
   } 
}

Upvotes: 5

Related Questions