Antipod Antipod - 1 year ago 293
C# Question

MongoDB C# driver, query by an array element using regex

I am using MongoDB C# driver version 2.2. My collection contains "Parent" objects. Each parent object has an array of children objects. Each child has name value:

"parent": {
{ "name": "Bob", "age": 10},
{ "name": "Alice", "age": 7},
{ "name": "Tobias", "age": 11}

I need to translate the following code into C# statements / LINQ syntax:

db.getCollection('Parents').find({'parent.children': { $elemMatch: { 'name': { $regex: '.*ob.*', $options: 'im' } }}})

I have found there are methods like

var builder = Builders<BsonDocument>.Filter;
builder.Regex("", new BsonRegularExpression(".*ob.*")); //does not work with array


builder.AnyEq("", "ob"); //without regex

But I cannot understand how to combine them. Please advise.


I am using the following for now, please correct me if you know a reason why it should not work correctly:

builder.AnyEq("", new BsonRegularExpression(".*ob.*"))

Answer Source

I am using the following for now:

builder.AnyEq("", new BsonRegularExpression(".*ob.*"))