Hi everyone,
I would like to obtain the results of a text search with the results of a regex. In particular, assuming that the input string is “substring”, I would like to be able to do the following filter:
{ $or : [ { name : { $regex : “.substring.” } }, {$text : { $search: “substring” } } ] }
Of course, I’ve previously created the $text index on “name” field, however it gives me a Mongo Error since $or and $text operator cannot be used together.
How can I achieve this filtering?
Thanks in advance
Hi @Matteo_Tarantino ,
Why do you need this kind of double search if you already perform a text search. In general we recommend using Atlas search for full text searches if it happens that your cluster is an Atlas cluster:
If you still insist on running this query using the traditional text indexes , I believe the use of $unionWith aggregation might work:
[{$match: {
$text: {
$search: 'substring'
}
}}, {$unionWith: {
coll: '<COLLECTION-NAME>',
pipeline: [
{
$match: {
name: {
$regex: '. substring.'
}
}
}
]
}}]
Ty
Hi @Pavel_Duchovny ,
to the best of my knowledge $search
operator does not find a match if the searching string is actually a substring of the field I’m seaching on. In particular:
Suppose that you are searching by name
and the name
field of a document is “Matteo”. If the searching string is “atte” the $search
operator discards that document. At leats I’m experiencing this behavior when applying the $search
operator in a serverless atlas cluster. Is it correct?
Hi @Matteo_Tarantino ,
Do you mean when using the “regex” operator in the $search stage of Atlas Search?
With regex operator (I linked you with…) you can search for partial expressions of a word:
[{$search: {
regex: {
path: 'title',
query: '.*los.*',
allowAnalyzedField: true
}
}}]
In this example I search the sample_mflix.movies
collection using a regex .*los.*
and it find strings like:
title : "Broken Blossoms or The Yellow Man and the Girl"
...
title : "The Lost World"
Thanks
Pavel
This operator concatenates two regular expressions a and b . No character represents this word combiner operator; you simply put b after a . The result is a regular expression that will match a string if a matches its first part and b matches the rest.
Hi @Richard_Gravener ,
I need an example document and query…
[$unionWith: coll: ‘COLLECTION-NAME>’, pipeline: [$match: name: $regex: ‘. substring.’ ] ]
example document have not show on this platform for this security reason. If want to see please visit …