从 $arrayElemAt 结果中选择字段

Min*_*ero 3 javascript mongoose mongodb 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'],
                  },
                ],
              },
            },
          },
        },
      },
    },
  ]);
Run Code Online (Sandbox Code Playgroud)

Ash*_*shh 6

只需.dot$staffUsers

{ "name": {
  "$arrayElemAt": [
    "$staffUsers.name",
    { "$indexOfArray": ["$staffUsers._id", "$$this.user_id"] }
  ]
}}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢它的工作原理。我实际上是这样写的,但没有尝试,因为我认为它行不通。哈哈。 (2认同)