mongodb how to project a field from an object returned by array $first, without $getField

Viewed 15

We are still on mongo 4.4 so, how do I get this result in my projection:

{ 
  districtId: 'xkj1',
  firstCollegeId: '123'
}

I'm trying to only return the FIRST element that has type: 'college', from this data:

{
  districtId: 'xkj1',
  students: {
    [{studentId: '123', type: 'college'}, {studentId: '124', type: 'highSchool'}]
  }
}

So far I can get the $first element of a $filter expression, but after that I'm stuck.

db.Collection1.aggregate(
  {
    $project: { 
      districtId: 1,
      firstCollegeId: {
        $first: {
          $filter: {
            input: "$students",
            as: "item",
            cond: { $eq: ["$$item.type", "college"] }
          }
        }
      }
    }
  }
)

so I am getting:

{ 
  districtId: 'xkj1',
  firstCollegeId: {studentId: '123', type: 'college'}
}

But that is too many fields. I cannot use $getField.

1 Answers

Simply add one more projection step:

  {
    $project: {
      _id: 0,
      districtId: 1,
      firstCollegeId: "$firstCollegeId.studentId"
    }
  }

See how it works on the playground example

Related