D
D
drowzeenico2015-02-25 11:58:11
MongoDB
drowzeenico, 2015-02-25 11:58:11

How to correctly sort by integer fields in MongoDB?

Hello.
Can't figure out how mongo sorts, though it should be simple.
There are documents:

[{name: 'x', sort: '10'},
{name: 'y', sort: '4'},
{name: 'z', sort: '1'}]

I'm trying to sort them by the sort (ASC) parameter, it gives a mess:
[{name: 'z', sort: '1'},
{name: 'x', sort: '10'},
{name: 'y', sort: '4'}]

Same for DESC, but in reverse order. What the heck? Why doesn't he do the usual? Why not [1, 4, 10] ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2015-02-25
@drowzeenico

That's right, it sorts strings, you need to set it as ints [{name: 'z', sort: 1}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question