MongoDB C# docs
GitHub.NET DriverMongoDB docs
  • ⭐Introduction
  • πŸ“ŒGetting started
    • Environment setup
    • πŸƒβ€β™‚οΈ Quick start
      • MongoDB connection
      • Databases
      • Collections
      • Insert documents
      • Read documents
      • Update documents
  • πŸ“‘CRUD Basics
    • βž•Create
      • Id Member
      • Ordered insert
    • πŸ”ŽRead
      • Basics
      • Comparison Operators
      • Logical Operators
      • Element Operators
      • Array operators
      • Evaluation Operators
    • πŸ“Update
      • Operators
      • Replace
      • Arrays
    • ❌Delete
  • πŸ§ͺAggregation
    • Overview
    • βœ‚οΈProject
    • 🎯Match
    • πŸ“¦Group
    • 🚩Unwind
    • ⏩Pagination
    • πŸ“ˆBucket
    • ✨Operators
Powered by GitBook
On this page
  • Overview
  • Regex operator - $regex
  • Text operator - $text
  1. CRUD Basics
  2. Read

Evaluation Operators

PreviousArray operatorsNextUpdate

Last updated 5 years ago

Overview

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

Regex operator - $regex

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.

Builders<User>.Filter
    .Regex(doc => doc.<field>, 
        new BsonRegularExpression(<regex-expression>))

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.

EvaluationOperators.cs
var collection = database
    .GetCollection<User>(Constants.UsersCollection);

// create a regular expression
var gmailFilter = Builders<User>.Filter
    .Regex(u => u.Email, 
    new BsonRegularExpression("/gmail/"));
    
var gmailUsers = await collection
    .Find(gmailFilter).ToListAsync();
var bsonCollection = database
    .GetCollection<BsonDocument>(Constants.UsersCollection);

// create a regular expression
var bsonGmailFilter = Builders<BsonDocument>
    .Filter.Regex("email", 
        new BsonRegularExpression("/gmail/"));

var bsonGmailUsers = await bsonCollection
    .Find(bsonGmailFilter).ToListAsync();
db.users.find({"email": { $regex : /gmail/ }})

--------------------

// sample result

{
   "_id": ObjectId("5eabe30dad09da9765850250"),
   "gender":1,
   "firstName":"Lee",
   "lastName":"Carroll",
   "userName":"Lee.Carroll33",
   "avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/hasslunsford/128.jpg",
   "email":"Lee.Carroll@gmail.com", // matched here
   "dateOfBirth":"ISODate("1957-02-25T12:56:15.974Z")",
   "address":{
      "street":"2303 Braxton Gardens",
      "suite":"Apt. 313",
      "city":"Greenfeldermouth",
      "state":"Delaware",
      "zipCode":"21308-0693",
      "geo":{
         "lat":-79.4473,
         "lng":-150.5346
      }
   },
   "phone":"544-623-0642",
   "company":{
      "name":"Little and Sons",
      "catchPhrase":"Adaptive neutral capability",
      "bs":"drive integrated technologies"
   },
   "salary":"NumberDecimal("1275")",
   "monthlyExpenses":2201,
   "favoriteSports":[
      "Golf",
      "Tennis",
      "Water Polo",
      "American Football",
      "Formula 1",
      "Cycling",
      "Table Tennis",
      "Boxing",
      "Volleyball",
      "Basketball"
   ],
   "profession":"Pilot"
}
public class User
{
    [BsonId]
    [BsonIgnoreIfDefault] // required for replace documents 
    public ObjectId Id { get; set; }
    public Gender Gender { get; set; }
    public string FirstName {get; set; }
    public string LastName {get; set; }
    public string UserName {get; set; }
    public string Avatar {get; set; }
    public string Email {get; set; }
    public DateTime DateOfBirth {get; set; }
    public AddressCard Address {get; set; }
    public string Phone {get; set; }
    
    [BsonIgnoreIfDefault]
    public string Website {get; set; }
    public CompanyCard Company {get; set; }
    public decimal Salary { get; set; }
    public int MonthlyExpenses { get; set; }
    public List<string> FavoriteSports { get; set; }
    public string Profession { get; set; }
}

MongoDB uses Perl compatible regular expressions version 8.42 with UTF-8 support

Text operator - $text

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.

EvaluationOperator
var productsCollection = database
                .GetCollection<Product>(Constants.ProductsCollection);
                
// create a text index on the name field                
productsCollection.Indexes
  .CreateOne(new CreateIndexModel<Product>
                (Builders<Product>.IndexKeys.Text(p => p.Name)));
db.products.createIndex( { "name": "text" } )

// Result
{
  "numIndexesBefore" : 1,
  "numIndexesAfter" : 2,
  "note" : "all indexes already exist",
  "ok" : 1
}

// sample document

{
  "_id" : ObjectId("5eac24240a037a3b4b412366"),
  "name" : "Awesome Concrete Shoes"
}
public class Product
{
    public ObjectId Id { get; set; }
    public string Name { get; set; }
}

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.

Builders<Product>.Filter.Text(string term);

The sample finds all Product documents that contain the term "shirt".

EvaluationOperator
var productsCollection = database
                .GetCollection<Product>(Constants.ProductsCollection);

// create a text search filter          
var searchFilter = Builders<Product>
                .Filter.Text("shirt");

var shirtsProducts = await productsCollection
                .Find(searchFilter).ToListAsync();

var productsBsonCollection = database
  .GetCollection<BsonDocument>(Constants.ProductsCollection);
  
var bsonSearchFilter = Builders<BsonDocument>
  .Filter.Text("shirt");
  
var bsonShirtsProducts = await productsBsonCollection
  .Find(bsonSearchFilter).ToListAsync();
db.products.find({ $text: { $search: 'shirt' } });

-------------------------
// sample results

{ 
  "_id" : ObjectId("5eac2a1a2d5d5e188996b00e"), 
  "name" : "Handcrafted Steel Shirt"
},
{ 
  "_id" : ObjectId("5eac2a1a2d5d5e188996affa"), 
  "name" : "Licensed Wooden Shirt" 
},
{ 
  "_id" : ObjectId("5eac2a1a2d5d5e188996afef"), 
  "name" : "Sleek Soft Shirt" 
}
public class Product
{
    public ObjectId Id { get; set; }
    public string Name { get; set; }
}

FilterDefinitionBuilder.Text method optionally accepts a TextSearchOptions instance where you can control the case sensitivity on your search query.

Builders<T>.Filter.Text(string term, 
    new TextSearchOptions() 
        { CaseSensitive = true });

Searches the specified term in the fields indexed with a

Text operator $text is used along with a 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.

πŸ“‘
πŸ”Ž
text index
text index
Evaluation operators