How to use $arrayElemAt and remove fields from that element in MongoDB $projection?

前端 未结 1 913
盖世英雄少女心
盖世英雄少女心 2021-02-14 19:21

I have \'jobs\' and \'users\' collection. Every user can create a job for given \'jobCategoryId\', that job is then saved in \'jobs\' collection and contains \'userId\' of it\'s

1条回答
  •  南笙
    南笙 (楼主)
    2021-02-14 20:00

    This is from the syntax of arrayElemAt

    The expression can be any valid expression as long as it resolves to an array.

    Which means you can construct your array elements however you want. In your case you want only the name. So this should work:

    [{
      $match: {
        jobCategoryId: mongoose.Types.ObjectId(jobCategoryId)
      }
    }, {  
      $lookup: {  
        from: 'users',
        localField: 'userId',
        foreignField: '_id',
        as: 'user'
      }
    }, {  
      $project: {  
        _id: 1,
        description: 1,
        title: 1,
        user: {  
          name: {
            $arrayElemAt: ["$user.name", 0]
          }
        }
      }
    }]
    

    Follow up UPDATE: it was asked how to additional properties on top of name . Here is the project:

    {  
      $project: {  
        _id: 1,
        description: 1,
        title: 1,
        user: {  
          name: {  
            $arrayElemAt: ["$user.name", 0]
          },
          email: {  
            $arrayElemAt: ["$user.email", 0]
          }
        }
      }
    }
    

    Second follow up as Drag0 asked in the comments: If the above isn't good enough because the results generate a user:[] array of size 1 instead of an object user:{} the following can be used.

    {  
      $project: {
        _id: 1,
        description: 1,
        title: 1,
        user: {
          $let: {
            vars: {
              firstUser: {
                $arrayElemAt: ["$user", 0]
              }
            },
            in: {
              name: "$$firstUser.name",
              email: "$$firstUser.email"
            }
          }
        }
      }
    }
    

    0 讨论(0)
提交回复
热议问题