[CSHARP-2976] Document How to do collations with LINQ Created: 20/Feb/20  Updated: 28/Oct/23  Resolved: 22/Oct/20

Status: Closed
Project: C# Driver
Component/s: Documentation, Linq
Affects Version/s: None
Fix Version/s: 2.12.0

Type: New Feature Priority: Major - P3
Reporter: Spencer Brown Assignee: Dmitry Lukyanov (Inactive)
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Case:

 Description   

A simple LINQ query where toUpper is used to effect a case-insensitive match becomes an aggregation with an anchored case-insensistive regex $match stage.

This works, but scans the entire index. Using a case-insensitive collation is a solution, but LINQ does not currently support collations in the MongoDB implementation.



 Comments   
Comment by Githook User [ 22/Oct/20 ]

Author:

{'name': 'DmitryLukyanov', 'email': 'dmitry.lukyanov@mongodb.com', 'username': 'DmitryLukyanov'}

Message: CSHARP-2976: Document How to do collations with LINQ.
Branch: master
https://github.com/mongodb/mongo-csharp-driver/commit/1b5894c9dd185465b790661c87bef3dcf67404e0

Comment by Robert Stam [ 10/Mar/20 ]

So as far as I can tell there is no LINQ feature related to collation, but since LINQ queries are converted to aggregation pipelines and MongoDB does have the notion of a collation that applies to an entire pipeline, there is a way to express that using the C# driver:

namespace ConsoleApplication
{
    public class C
    {
        public int Id { get; set; }
        public string S { get; set; }
    }   
 
    public class Program
    {
        public static void Main()
        {
            var client = new MongoClient("mongodb://localhost");
            var database = client.GetDatabase("test");
            var collection = database.GetCollection<C>("test");
 
            database.DropCollection("test");
            collection.InsertOne(new C { Id = 1, S = "Tom" });
            collection.InsertOne(new C { Id = 2, S = "tom" });
            collection.InsertOne(new C { Id = 3, S = "Mary" });
 
            var collation = new Collation("en_US", strength: CollationStrength.Secondary);
            var aggregateOptions = new AggregateOptions { Collation = collation };
            var query = collection
                .AsQueryable(aggregateOptions)
                .Where(x => x.S == "tom");
            var result = query.ToList();
        }
    }
}

That worked for me. Do you think that is what you are asking for?

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