【问题标题】:MongoDB: Sort UTF-8 stringsMongoDB:对 UTF-8 字符串进行排序
【发布时间】:2019-04-09 02:17:47
【问题描述】:

我有这个聚合,我正在使用小写和 UTF-8 对字段 (_id.name) 进行排序,但我无法对 "á" 或 "Á" 之类的字符串进行排序喜欢。如何对 utf-8 和小写字符串进行排序?

聚合:

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
    }

编辑

现在我使用这样的排序规则:

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

错误: MongooseError: Callback must be a function, got [object Object]

【问题讨论】:

标签: mongodb sorting mongoose nosql aggregation-framework


【解决方案1】:

在此处使用collationlocale: "en"

通过聚合你可以做这样的事情(mongodb)

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

使用 mongoose,您可以在架构中使用 collation

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

Schedule.aggregate([{ "$sort": { "_id.name": 1 }}]).exec((error, response) => {
  console.log(response)
})

【讨论】:

  • 我编辑了我的答案以显示错误和我现在的代码,错误是“MongooseError: Callback must be a function, got [object Object]”
  • @Matheus 我已经更新了我的答案,请看一下
  • 这里,不起作用,因为我使用的是 'pt'(葡萄牙语)并且排序无法正常工作,我不知道为什么
  • 你能用样本集编辑你的问题吗?
猜你喜欢
  • 2010-11-02
  • 2011-08-24
  • 2011-12-17
  • 2018-08-19
  • 1970-01-01
  • 2011-07-02
  • 1970-01-01
  • 2023-03-06
  • 2023-03-18
相关资源
最近更新 更多