simon
simon

Reputation: 375

mongodb unwind and sort array nested inside an array of documents

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.

Upvotes: 3

Views: 1409

Answers (2)

turivishal
turivishal

Reputation: 36104

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 } }
)

Upvotes: 2

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 } }
    ])

Upvotes: 6

Related Questions