Dimas
Dimas

Reputation: 67

Mongoose / mongoDB - How to sort by string?

May somebody help me how to short string at mongo.

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

and here's the result :

[
  { _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 }
]

I have stuck why _id : 11 is after _id : 1.

Please if there's anyone can help me with this. Thank you very much.

Upvotes: 1

Views: 559

Answers (1)

varman
varman

Reputation: 8894

MongoDB can't sort by numbers stored as String. Here is the workaround

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

Working Mongo playground

Upvotes: 1

Related Questions