Mongo C# driver - Contains Filter
Solution 1
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())
{
// ...
}
Solution 2
In order to achieve that in V2 API, use the `Filter.Regex':
var collection = db.GetCollection<BsonDocument>("collection");
var filter = Builders<BsonDocument>.Filter.Regex("fieldName", new BsonRegularExpression(".*fieldValue.*"));
var data = await (await coll.FindAsync<BsonDocument>(filter).ConfigureAwait(false)).ToListAsync();
//continue process data
Solution 3
First, I highly recommend taking MongoDB University's .NET course (from Mongo itself). It's really thorough, and covers your question (and more) in depth.
Second, I assume that x
is an array in your example.
MongoDB correctly handles polymorphism with arrays. If you have a class Post
with an array of Tags
, you can filter where Tag = ABC
.
If you're using the C# linq methods, that looks like .Find(p => p.Tags == "ABC")
. If you're using BsonDocument
, that looks like new BsonDocument().Add("Tags", "ABC")
.
Solution 4
I was able to get this working using Filter.AnyIn like so
var filter = Builders<BsonDocument>.Filter.AnyIn("x", new List<string> { "ABC" });
This works if you're looking for multiple values too, just add them to the list.
Mr767267
Updated on August 18, 2021Comments
-
Mr767267 over 2 years
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'
-
Mr767267 over 8 yearsThanks! I am using 2.0 version of driver and could not .Matches() on Filter Builder, but I could find .Regex(), so I'll try with that.
-
Yiannis P. about 8 yearsYour builder method for the filter isn't correct. It cannot be Equal to since you're looking for Contains.