[CSHARP-1601] Query MongoDb sublists with C# LINQ regex Created: 11/Mar/16  Updated: 02/Feb/22  Resolved: 02/Feb/22

Status: Closed
Project: C# Driver
Component/s: Linq
Affects Version/s: 2.2.3
Fix Version/s: None

Type: Bug Priority: Minor - P4
Reporter: Søren Holstebroe Assignee: Unassigned
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Epic Link: CSHARP-3615

 Description   

As posted here:
http://stackoverflow.com/questions/35863999/query-mongodb-sublists-with-c-sharp-linq-regex

Regex IsMatch does not seem to work on list-properties although the same LINQ query runs fine on a standard list.

I.e. given

public class Car

{ public string Name; public List<string> Colors; }

this only works for plain list LINQ:

var regex = new Regex("^Blue.*");
var matchingCars = carCollection.Where(x => x.Colors.Any(y => regex.IsMatch));

The above just silently returns an empty queryable.



 Comments   
Comment by James Kovacs [ 02/Feb/22 ]

Re-tested with .NET/C# driver v2.14.1 with both LINQ2 and LINQ3 implementations. Both produce correct results.

using System.Text.RegularExpressions;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
 
var settings = new MongoClientSettings { LinqProvider = LinqProvider.V3 };
var client = new MongoClient(settings);
var db = client.GetDatabase("test");
var coll = db.GetCollection<Car>("cars");
 
var regex1 = new Regex("^Volvo.*");
var matchingCars1 = coll.AsQueryable().Where(x => regex1.IsMatch(x.Name));
Console.WriteLine(matchingCars1);
foreach (var car in matchingCars1)
{
    Console.WriteLine(car);
}
 
var regex2 = new Regex("^Blue.*");
var matchingCars2 = coll.AsQueryable().Where(x => x.Colors.Any(y => regex2.IsMatch(y)));
Console.WriteLine(matchingCars2);
foreach (var car in matchingCars2)
{
    Console.WriteLine(car);
}
 
public class Car
{
    public ObjectId Id { get; set; }
    public string Name { get; set; }
    public List<string> Colors { get; set; }
    public override string ToString() => $"{Name}: {string.Join(", ", Colors)}";
}

LINQ3 output:

test.cars.Aggregate([{ "$match" : { "Name" : /^Volvo.*/ } }])
Volvo: Red, Blue, Black, Turquoise
test.cars.Aggregate([{ "$match" : { "Colors" : /^Blue.*/ } }])
Volvo: Red, Blue, Black, Turquoise
Honda: Red, Blue, Black, Auburn
Jaguar: Blue

Please re-open with additional details if the query is not behaving as you expect.

Generated at Wed Feb 07 21:40:06 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.