Home > database >  MongoDB - How to access a newly created array field created with $lookup and aggregate function
MongoDB - How to access a newly created array field created with $lookup and aggregate function

Time:10-13

Assuming I have two collections:

courses:

[
  {
    _id: 1,
    name: "Geometry",
    teacher_id: 1
  },
  {
    _id: 2,
    name: "English",
    teacher_id: 2
  }
]

teachers:

[
  {
    _id: 1,
    firstName: "John",
    lastName: "Adams"
  },
  {
     _id: 2,
     firstName: "Mary",
     lastName: "Jane"
  }
]

Now I perform an aggregation on the two collections to create something similar to a join in SQL:

db.collection("courses").aggregate([
      {
        $lookup:{
              from: "teachers",
              localField: "teacher_id",
              foreignField: "_id",
              as: "teacher_info"
          }
      },
      {
        $match:{
          //I want to perform a match or filter here on the teacher_info
        }
      }
]);

The $lookup and aggregation will return a list of documents that have a new teacher_info array field.

[
  {
    _id: 1,
    name: "Geometry",
    teacher_id: 1,
    teacher_info: [
      {
        _id: 1,
        firstName: "John",
        lastName: "Adams"
      },
   ]
  },
  {
    _id: 2,
    name: "English",
    teacher_id: 1,
    teacher_info: [
      {
         _id: 2,
         firstName: "Mary",
         lastName: "Jane"
      },
   ]
  }
]

I need to perform a match operation in the newly created teacher_info array field. For example, only keep the teacher that has the first name "John". How can I do so? Is that possible?

CodePudding user response:

You can work with dot notation in your $match stage.

{
  $match: {
    "teacher_info.firstName": "John"
  }
}

Demo @ Mongo Playground

  • Related