Hi Maddy,
As Stone pointed out, MongoDB is treating this field as a string. This means it treats everything within this field as a character, even numbers.
Typically e.g. in programming languages, non-default sort order can be achieved by passing a custom sort function. However currently in MongoDB 3.4.4, there is no method to do so. However, there is an open ticket for this feature:
SERVER-153. Also related to this:
SERVER-14784. Please watch/upvote those tickets if you feel this feature is important for you.
There are different approaches that you could use in order to obtain the result you are expecting.
- First approach would be to divide the job field into two separate fields: the job string part and the job number part.
{"job":"Job1"} -> {"job":"Job1","job_string":"Job","job_number":1}
{"job":"Job100"} -> {"job":"Job100","job_string":"Job","job_number":100}
You can then sort the documents with:
db.collection.find(...).sort({job_string: 1, job_number: 1})
- Second approach would be zero-padding the string+number into a uniform length. For example:
{"job":"Job1"} -> {"job":"Job001"}
{"job":"Job100"} -> {"job":"Job100"}
If you still have issues, please post your MongoDB version and some example documents.
Regards,
Conchi