C# Driver, using linq's In operater ($in) for regex

1,799 views
Skip to first unread message

Sam Martin

unread,
Oct 8, 2012, 4:44:09 PM10/8/12
to mongod...@googlegroups.com
Hi all,

think this should be a simple one, but cant suss the syntax.

In mongo i can say

db.coll.find({ "myatt": { $in : [/^x/,/^y/]} });

Is this possible using the "In" linq to mongo extension method?

I've tried passing the string[] as regex string but no surprise didn't work, do I have to use Inject()?

TIA
Sam

Robert Stam

unread,
Oct 8, 2012, 5:05:59 PM10/8/12
to mongod...@googlegroups.com
This can't really be expressed in standard LINQ because the types involved (string and BsonRegularExpression) are different. The standard LINQ Contains extension method (and the analogous LINQ to MongoDB In extension method) assumes that the value being tested and the source of values to test against are of the same type.

Inject seems like a good workaround.

Do you feel there should be a way to express this type-mismatched query directly in LINQ to MongoDB? If so, you could create a new JIRA issue requesting the feature.

Sam

--
You received this message because you are subscribed to the Google
Groups "mongodb-user" group.
To post to this group, send email to mongod...@googlegroups.com
To unsubscribe from this group, send email to
mongodb-user...@googlegroups.com
See also the IRC channel -- freenode.net#mongodb

craiggwilson

unread,
Oct 8, 2012, 5:19:39 PM10/8/12
to mongod...@googlegroups.com
JIRA already exists: https://jira.mongodb.org/browse/CSHARP-495 and a related issue https://jira.mongodb.org/browse/CSHARP-493.  I have the code done for the fix, but we weren't (and still aren't) sure if this is supposed to work or if it just happens to work (and might go away later).

AG

unread,
Oct 30, 2012, 9:16:00 PM10/30/12
to mongod...@googlegroups.com
Is there a way to express the $in query using regular expressions in the c# driver?

Something like this, but checking the regex against any member in the array?

Query.Matches("Series", BsonRegularExpression.Create(new Regex(searchPattern, RegexOptions.IgnoreCase)))

Thanks.

Sam Martin

unread,
Oct 30, 2012, 9:30:27 PM10/30/12
to mongod...@googlegroups.com
here's one i've used a bit.

It returns documents where one of the elements in the series array exists in an collection of regular expressions created from a string array.

i.e. all docs where at least one of the Series elements starts with one of the items in my string array. /^xxxx/, /^yyyy/

_db.GetCollection("mycollection").Find(Query.In("Series", mystringrray.Select(p => BsonRegularExpression.Create("/^" + p + "/")));

does that help?


--
Reply all
Reply to author
Forward
0 new messages