I tried to set up a scenario as close as possible to yours, and I got some interesting results.
1. I created a database named dados
2. I created a collection named grpdados
And I've added 4
documents in collection grpdados
:
{
"_id": {
"$oid": "5b5923b4fb6fc07c4c24156e"
},
"sq_itemgrupodados": "1"
},
{
"_id": {
"$oid": "5b592417fb6fc07c4c241593"
},
"sq_itemgrupodados": "2"
},
{
"_id": {
"$oid": "5b5923fcfb6fc07c4c24158e"
},
"sq_itemgrupodados": "3"
},{
"_id": {
"$oid": "5b592429fb6fc07c4c241595"
},
"sq_itemgrupodados": "10"
}
After that, I searched for sq_itemgrupodados
and ordered using sort()
upwards:
dados.grpdados.sort({"sq_itemgrupodados":1})
Result:
{1, 10, 2, 3}
Exactly like yours, all right up to here!
So I made a small change to the documents, instead of passing string
, I changed it to the value inteiro
, example:
{
"_id": {
"$oid": "5b5923b4fb6fc07c4c24156e"
},
"sq_itemgrupodados": 1
}
Doing this for the 4
documents, and doing the search again and sorting with sort()
:
Result:
{1,2,3,10}
( sorted in ascending order as we wanted! )
Conclusion
I think it was just a misconception about the type of data you are trying to sort, for string
it will sort by the value of the table ascii , logo 10 < 2
and 10 < 3
.
EDIT: I created a sandbox for testing on mongolab , so if that does not solve we can try other alternatives: