Home > Software engineering >  Combine aggragate with search - Moongose
Combine aggragate with search - Moongose

Time:04-07

I'm having a collection of students:

[  
  {  
    _id: 123,
    firstName: 'Tom', 
    lastName: 'Bo',  
    instructorsIds: ['12', '13', '14'] 
  }  
]

I'm getting query params from front-end, to filter the database:

{ 
  instructorId: '13', 
  name: 'To' 
}

The filters should work like: AND

And name filter should combine firstName and lastName of student and then search. I've managed to do something like:

studentModel.aggregate([
  {
    $addFields: {
      nameFilter: {
        $concat: [
          "$firstName",
          " ",
          "$lastName"
        ]
      }
    }
  },
  {
    $match: {
      nameFilter: {
        $regex: filters.studentName,
        $options: "i"
      }
    }
  }
]) 

But I don't know how to add AND filter od instructor id into it. Appreciate the help, thanks

CodePudding user response:

db.collection.aggregate([
  {
    $addFields: {
      nameFilter: {
        $concat: [
          "$firstName",
          " ",
          "$lastName"
        ]
      }
    }
  },
  {
    $match: {
      nameFilter: {
        $regex: "To",
        $options: "i"
      },
      instructorsIds: "13"
    }
  }
])

https://mongoplayground.net/p/-zq0jWnQhU_

  • Related