从$ arrayElemAt结果中选择字段

时间:2019-05-14 16:24:31

标签: javascript mongodb mongoose mongodb-query aggregation-framework

$arrayElemAt内的$map选择特定字段。 我只想选择$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'],
                  },
                ],
              },
            },
          },
        },
      },
    },
  ]);

1 个答案:

答案 0 :(得分:0)

只需将.dot$staffUsers一起使用

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