I’m trying to implement a LIKE operator with $elemMatch
and $regex
to find any document that match the search term I’m passing but I can’t figure out how to do that.
The collection I have:
{
...others arrays,
"discounts": [
{
"_id": "628fd4cd7176540e9e1ad6c2",
"name": "asd < % $",
"code": "EGX2-VA2Q-H9LV",
"createdAt": "2022-05-26T19:28:13.168Z",
"updatedAt": "2022-05-26T19:28:13.168Z"
},
{
"_id": "62e28bf56b91f508bbd8b703",
"name": "test edit",
"code": "51AD-QBQG-TRNJ",
"createdAt": "2022-07-28T13:15:33.140Z",
"updatedAt": "2022-07-28T13:15:33.140Z"
}
],
...others fields
}
What I’m trying to do:
db.Store.find(
$or: [
{
discounts: {
$elemMatch: { name: { $regex: searchTerm, $options: 'i' } }
}
},
{
discounts: {
$elemMatch: { code: { $regex: searchTerm, $options: 'i' } }
}
}
])
The result of this always return all documents of discounts array. If I hardcoded the search term, like:
{
discounts: {
name: 'test edit'
}
}
I get the same result, all documents.
What Am I doing wrong here? Thanks!