1

I have a table in MongoDB in which I can get the fields in descending order sorted by system_id

db.job_parameters_mongo.find().sort({system_id : -1})

This is fine but gives me incorrect result as system_id is string field.Is there any way that I can convert system_id to number before ordering in descending order.I saw on this site that there is a way to do this using forEach (how to convert string to numerical values in mongodb) but that uses a function.Isn't there any other way like we have to_number in rdbms?

handlerFive
  • 870
  • 10
  • 23
Chirayu Sharma
  • 75
  • 1
  • 11

1 Answers1

1

You can use $toInt available in 4.0 version.

db.job_parameters_mongo.aggregate([
 {"$addFields":{"system_id":{"$toInt":"$system_id"}}}, 
 {"$sort":{"system_id":-1}}
])
s7vr
  • 73,656
  • 11
  • 106
  • 127
  • Thanks for your prompt reply.I tried executing db.job_parameters_mongo.aggregate([{"$addFields":{"system_id":{"$toInt:"$system_id"}}},{"$sort":{"system_id":-1}}]) but getting error 2018-09-05T20:44:59.111+0530 E QUERY [js] SyntaxError: missing : after property id @(shell):1:72 .Is there any colon missing – Chirayu Sharma Sep 05 '18 at 15:19
  • yw. yeah missing closing quotes after $toInt. Try `[{"$addFields":{"system_id":{"$toInt":"$system_id"}}},{"$sort":{"system_id":-1}}]`. Updated answer as well. – s7vr Sep 05 '18 at 15:20