Marco Talento
Marco Talento

Reputation: 2395

mongodb c# $regex

I'm creating mongodb queries dynamically but when I use $regex it throws an exception. The query works if I use it directly in the shell!

Any suggestions? I really need to use dynamic queries.

method: this.Collection.Find(query).Limit(limit).ToListAsync(cancellationToken);

query: { $and: [ { Name: { '$regex': /batman/i } } ] }

exception:'BsonSerializer.Deserialize<BsonDocument>("{ $and: [ { Name: { '$regex': /batman/i } } ] }")' threw an exception of type 'System.FormatException'
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233033
HelpLink: null
InnerException: null
Message: "JSON reader expected a string but found '/batman/i'."
Source: "MongoDB.Bson"

Upvotes: 0

Views: 248

Answers (1)

4J41
4J41

Reputation: 5095

You can try separating the options from the search value.

{ $and: [ { Name: { '$regex': 'batman', '$options' : 'i' } } ] }

Upvotes: 1

Related Questions