I am trying to search for users based on their names. My user schema looks like:
user: {
firstName: string,
lastName: string,
...
}
I can run the following query fine:
const userDocs = await UserModel
.find({
$expr: {
$eq: [
{
$concat: [
'$firstName',
' ',
'$lastName',
],
},
'John Doe',
],
},
});
However I am trying to run a query such as this:
const userDocs = await UserModel
.find({
$expr: {
$regex: [
{
$concat: [
'$firstName',
' ',
'$lastName',
],
},
new RegExp(`^${text}`, 'i'),
],
},
});
However MongoDB does not support this.
Is there a way to use $regex
with a $concat
?
Aggression expression don't support regex expression query expression do.
Try aggregate
Create a extra field name in the aggregation pipeline combining first name and last name followed by match with regular expression.
const userDocs = await UserModel.aggregate
({$addFields:{
name:{
$concat:[
'$firstName',
' ',
'$lastName',
]
}
}},
{$match:{
name:new RegExp(`^${text}`, 'i')
}});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With