3

How to make sorting functional well if it is case sensitive. how can we make it correct

Please suggest best way to fix it

db.products.aggregate([
  {
    "$unwind": "$receipe"
  },
  {
    "$unwind": "$receipe.burger"
  },
  {
    "$sort": {
      "receipe.burger.name": 1
    }
  }
])

https://mongoplayground.net/p/2pnUABI_-Mr

in my example familyburger should display first rather than Paneer Burger.

2 Answers 2

6

Demo - https://mongoplayground.net/p/Vt3GQx0tdXC

  • Add a new filed with to lower case using $toLower
  • Sot on the lower case value

   db.products.aggregate([
      { "$unwind": "$receipe" },
      { "$unwind": "$receipe.burger" },
      { $addFields: { "insensitiveName": { $toLower: "$receipe.burger.name" } } },
      { $sort: { "insensitiveName": 1 } }
    ])
Sign up to request clarification or add additional context in comments.

Comments

2

Specify collation option caseLevel in your query,

Flag that determines whether to include case comparison at strength level 1 or 2, If true, include case comparison.

db.products.aggregate(
  [
    { "$unwind": "$receipe" },
    { "$unwind": "$receipe.burger" },
    { "$sort": { "receipe.burger.name": 1 } }
  ],
  { collation: { locale: "en", caseLevel: true } }
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.