Home > Net >  Mongodb query distinct sort by numerical order
Mongodb query distinct sort by numerical order

Time:07-08

I am trying to sort the mongodb collection distinct output in numerical order. but I am getting the error message.

This query works, but its not sorting by numeric value.

db.cars.distinct( "carId").sort()

Trying this query, its giving the error message:

db.cars.distinct( "carId").sort().collation({
    locale: "en_US",
    numericOrdering: true
})

Error:

TypeError: (intermediate value).collation is not a function at user_script:34:64 at async ShellEvaluator.innerEval (all-standalone.js:6436:1758) at async ShellEvaluator.customEval (all-standalone.js:6436:1902)

How to sort this in numeric order?

Thanks

CodePudding user response:

If you want to use mongoDB to sort, one option is:

db.collection.aggregate([
  {$group: {_id: "$carId"}},
  {$sort: {_id: 1}},
  {$group: {_id: 0, res: {$push: "$_id"}}}
])

See how it works on the playground example

  • Related