简体   繁体   中英

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 AZ 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

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.

排序规则 caseFirst = "upper"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM