Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Sort UTF-8 strings

I have this aggregate and i was sorting a field (_id.name) with lowerCase and UTF-8, but i can't sort the strings like "á" or "Á" or anything like. How can i sort utf-8 and lowerCase strings?

Aggregate:

Schedule.aggregate([{
      $match: {
        store: req.body.store,
        scheduleStart: {
          $lte: start,
          $gte: req.body.period
        },
        status: {
          $in: resultStatus
        }
      }
    },
    {
      $group: {
        _id: {
          name: "$employee.name",
          id: "$employee.id"
        },
        totalValue: {
          $sum: "$value"
        },
        totalServices: {
          $sum: 1
        },
        totalComission: {
          $sum: "$comissionValue"
        }
      }
    },
    {
      '$addFields': {
        'ticket': {
          '$divide': ['$totalValue', '$totalServices']
        }
      }
    },
    {
      $sort: {
        "_id.name": 1
        }
    },
    {
      $skip: req.body.limit * req.body.page
    }

Edit

Now I using collation like this:

 Schedule.aggregate([{
     ...     
    {
      $sort: {
        "_id.name": 1
      }
    },
    {
      $skip: req.body.limit * req.body.page
    }

  ], { "collation": { "locale": "pt" }}).exec((error, response) => {
    if (error) res.status(500).send({
      error,
      code: 0,
      message: langs[req.query.lang].somethingWentWrong
    });

The ERROR: MongooseError: Callback must be a function, got [object Object]

like image 698
Matheus Barem Avatar asked Nov 16 '25 18:11

Matheus Barem


1 Answers

Use collation here with locale: "en"

With aggregation you can do something like this (mongodb)

Schedule.aggregate([{ "$sort": { "_id.name": 1 }}], { "collation": { "locale": "en" }})

With mongoose you can use collation inside your schema

var schema = new Schema({
  name: String
}, { collation: { locale: 'en' })

Schedule.aggregate([{ "$sort": { "_id.name": 1 }}]).exec((error, response) => {
  console.log(response)
})
like image 144
Ashh Avatar answered Nov 18 '25 18:11

Ashh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!