Minus Zero
Minus Zero

Reputation: 85

Pick field from $arrayElemAt result

Pick specific field from $arrayElemAt inside $map. I want to pick only the name field returned from the object at $arrayElemAt

const data = await this.aggregate([
    {
      $match: { provider_id: providerId },
    },
    {
      $lookup: {
        from: 'users',
        localField: 'staff.user_id',
        foreignField: '_id',
        as: 'staffUsers',
      },
    },
    {
      $project: {
        staff: {
          $map: {
            input: '$staff',
            in: {
              _id: '$$this._id',
              email_login: '$$this.email_login',
              full_calendar_view: '$$this.full_calendar_view',
              verified: '$$this.verified',
              user_id: '$$this.user_id',
              description: '$$this.description',
              name: {
                $arrayElemAt: [
                  '$staffUsers',
                  {
                    $indexOfArray: ['$staffUsers._id', '$$this.user_id'],
                  },
                ],
              },
            },
          },
        },
      },
    },
  ]);

Upvotes: 6

Views: 2590

Answers (1)

Ashh
Ashh

Reputation: 46441

Simply use .dot with the $staffUsers

{ "name": {
  "$arrayElemAt": [
    "$staffUsers.name",
    { "$indexOfArray": ["$staffUsers._id", "$$this.user_id"] }
  ]
}}

Upvotes: 8

Related Questions