Evaluation Operators
Last updated
Last updated
Evaluation operators are used to match documents based on some type of evaluation applied on the field values, for example, find all documents that one of their field values matches a specified Regex pattern. The evaluation applied on this example is to check if a field's value matches the regex pattern given.
Operator
Description
Regex
Find documents where their field values match a specified regular expression
Text
Searches the specified term in the fields indexed with a text index
The Regex operator is used when you want to match documents based on a regular expression. The regular expression is evaluated to one or more specified document fields. The $regex operator can be created via the driver by creating a FilterDefinition
with the Regex
function. Then use this filter definition in the IMongoCollection<T>.Find
method.
The sample finds all User
documents that their email field contains the "gmail" word. It does this by evaluating if there's a match between the email field and the regular expression, which by the way can be as complex as you wish.
MongoDB uses Perl compatible regular expressions version 8.42 with UTF-8 support
Text operator $text is used along with a text index for searching a term among string content inside documents. The text index indexes string content as if it was an array of string values while stops and stems all words. This means that it words in sentences such as "and", "or", "it" or "is" are ignored.
You can create a text index using the C# driver using an instance of CreateIndexModel<T>
. The following snippet creates a text index on the Name string field of the Product
class.
In case the index already exists, nothing will change
To create a search text query use the FilterDefinitionBuilder.Text
method to build a filter definition.
The sample finds all Product
documents that contain the term "shirt".
FilterDefinitionBuilder.Text
method optionally accepts a TextSearchOptions
instance where you can control the case sensitivity on your search query.