'Combine aggragate with search - Moongose
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
Solution 1:[1]
db.collection.aggregate([
{
$addFields: {
nameFilter: {
$concat: [
"$firstName",
" ",
"$lastName"
]
}
}
},
{
$match: {
nameFilter: {
$regex: "To",
$options: "i"
},
instructorsIds: "13"
}
}
])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | YuTing |
