Search code examples
c#mongodbmongodb-.net-drivermongodb-csharp-2.0

Mongo C# driver - Contains Filter


I am using the latest version of Mongo C# driver which uses a lot of Async and builder pattern. Which is nice. I am trying to convert SQL where clauses into Mongo FilterDefinition object.

Any idea how to handle "contains"?
like:

where x contains 'ABC'

Solution

  • If x is a string, you could do so with a simple regex. For the 2.0 driver, you can manually create the FilterDefinition:

    FilterDefinition<BsonDocument> filter = "{ x : { $regex : /ABC/ } }";
    

    Or build the filter use the Builder:

    var builder = Builders<BsonDocument>.Filter;
    var filter = builder.Matches("x", "ABC");
    

    Then you can use the filter in your query:

    using (var cursor = await collection.Find(filter).ToCursorAsync())
    {
        // ...
    }