admin管理员组

文章数量:1392105

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'],
                  },
                ],
              },
            },
          },
        },
      },
    },
  ]);

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'],
                  },
                ],
              },
            },
          },
        },
      },
    },
  ]);
Share Improve this question edited May 14, 2019 at 19:25 Ashh 46.6k16 gold badges111 silver badges137 bronze badges asked May 14, 2019 at 16:24 Minus ZeroMinus Zero 852 silver badges7 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

Simply use .dot with the $staffUsers

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

本文标签: javascriptPick field from arrayElemAt resultStack Overflow