猫鼬/ mongoDB-如何按字符串排序?

问题描述

愿有人帮助我如何在mongo上使弦短。

     [{
        "$group": {
            "_id": "$bulan","total_vote": {
                "$sum": {
                    "$multiply": "$nilai"
                }
            },"count": {
                "$sum": 1
            }
        }
    },{
        "$sort": {
            "_id": 1
        }
    }],

结果如下:

[
  { _id: '1',total_vote: 142,count: 23 },{ _id: '11',total_vote: 50,count: 1 },{ _id: '2',total_vote: 320,count: 160 },{ _id: '3',total_vote: 94,count: 47 },{ _id: '4',total_vote: 120,count: 60 },{ _id: '5',total_vote: 650,count: 13 },{ _id: '7',total_vote: 350,count: 7 },{ _id: '8',total_vote: 102,count: 2 }
]

我一直坚持为什么_id:11在_id:1之后。

如果有人可以帮助我。 非常感谢。

解决方法

MongoDB无法按存储为String的数字排序。这是解决方法

[
  {
    "$addFields": {
      newId: {
        $toInt: "$_id"
      }
    }
  },{
    "$sort": {
      newId: 1
    }
  },{
      $project:{
          newId:0
      }
  }
]

工作Mongo playground

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...