At the moment, I currently have a "like" statement that works great for strings.
Builders<Book>.Filter.Regex("subject", new BsonRegularExpression(searchString.ToString(), "i"));
At the moment I'm trying to query the years and possibly search by 2 digit pattern such as 99
, 98
.
Some of the options I currently have in the documents are 2000, 1998, 1997, 1996
.
If I query 98, the document with 1998 should be selected.
Unfortunately, the regex didn't work, wondering if I may get any tips or suggestions for integer number pattern with MongoDB C#.
CodePudding user response:
To work the regex with a numeric value, you need to cast it to a string first.
To do so, you need $regexMatch
and $toString
operators. As both operators are aggregation operators, you need to use $expr
as well.
I think there is no supported feature/function for these operators in MongoDB .Net Driver, but you can provide the query as a BsonDocument
.
filterDefinition &= new BsonDocument("$expr",
new BsonDocument("$regexMatch",
new BsonDocument
{
{ "input", new BsonDocument("$toString", "$year") },
{ "regex", year },
{ "options", "i" }
}
)
);
So the filter query will be translated as below:
find({ "subject" : /(?:)/i,
"$expr" : { "$regexMatch" : { "input" : { "$toString" : "$year" }, "regex" : "98", "options" : "i" } } })
Sample input data
Debugging & Output Result