SHIVAM SHARMA
SHIVAM SHARMA

Reputation: 404

How to implement a case insensitive sort with aggregate in mongodb (3.4)

I'm trying to implement a sort in MongoDB. But I'm getting an issue that my sort first includes the capital letters A-Z text & then small letters. I don't want them. I want the sort to be independent of the case. Here is my query,

var partnerCollection = [
      from: "courses",
      localField: "_id",
      foreignField: "partnerId",
      as: "courses"
    } },
    {
        $project:
        {
            "_id":1,
            "partnerName":1,
            "phone":1,
            "email":1,
            "courses.courseName": 1,
            "courses.courseType":1,
        }
    },
    {
        $match: findUserDataCondition
    },
    { $sort: { "partnerName" : 1 } },
    { $skip: start },
    { $limit: length }
];

If I sort with partnerName, I'm getting result as ABC, DEF, EFG , bcd, cde

My expected result is ABC, bcd, cde, DEF, EFG. Please hekp me in sorting this issues

Upvotes: 3

Views: 3520

Answers (1)

Valijon
Valijon

Reputation: 13103

Luckily, since MongoDb v3.4 the collation option has been introduced to specify language-specific rules for string comparison:

db.partnerCollection.aggregate([
  ...
],
{
  collation: {
      locale : "en"
  }
})

Note: If you also specify caseFirst = "upper" parameter, upercase string will be ordered before lowercase.

Collation with caseFirst = "upper"

Upvotes: 8

Related Questions