BsonString ordering in C#-driver differs from mongodb BsonString ordering

While working with BsonString as identificator I noticed that mongodb orders them with respect to register but C# driver does not. For example, mongodb sorts BsonString( “a”), BsonString( “B”) in order “B” then “a”, while driver sorts them in order BsonString( “a”) then BsonString( “B”). Is it bug or feature? :slight_smile:

1 Like

Hi, @astakhova.ksen.762,

Welcome to the MongoDB Community Forums. I understand that you have a question about differing sort behaviour between MongoDB and the MongoDB .NET/C# Driver.

I wouldn’t say this is a feature but more a consequence of different defaults. C# defaults to sorting strings based on current culture whereas MongoDB defaults to an ordinal sort.

using System;

var items = new[]{ "a", "B", "b", "A" };

Array.Sort(items, StringComparer.CurrentCulture); // default, sort based on current culture
Console.WriteLine(string.Join(", ", items));  // a, A, b, B

Array.Sort(items, StringComparer.Ordinal); // sort by underlying numeric representation
Console.WriteLine(string.Join(", ", items));  // A, B, a, b

MongoDB defaults to an ordinal sort by default. In mongosh:

Enterprise test> db.items.find({}).sort({v:1}) // ordinal sort
  { _id: ObjectId("64bfee537bb12babe73bf8cb"), v: 'A' },
  { _id: ObjectId("64bfee537bb12babe73bf8c9"), v: 'B' },
  { _id: ObjectId("64bfee537bb12babe73bf8c8"), v: 'a' },
  { _id: ObjectId("64bfee537bb12babe73bf8ca"), v: 'b' }

You can change this by creating an index with collation and specifying the collation for the field:

Enterprise test> db.items.createIndex({v:1}, {collation: { locale: "en_US" }})
Enterprise test> db.items.find({}).sort({v:1}).collation({locale: "en_US"})
  { _id: ObjectId("64bfee537bb12babe73bf8c8"), v: 'a' },
  { _id: ObjectId("64bfee537bb12babe73bf8cb"), v: 'A' },
  { _id: ObjectId("64bfee537bb12babe73bf8ca"), v: 'b' },
  { _id: ObjectId("64bfee537bb12babe73bf8c9"), v: 'B' }

Hopefully the differing behaviour makes sense now.


Thank you!
Does driver have a comparer that considers collation or its absence? It would be nice feature-request if the answer is no

Hello, @James_Kovacs!
I forgot to mention you in the previous message so I suppose you haven’t seen it yet

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.