Skip to content

Instantly share code, notes, and snippets.

@jmikola
Created February 12, 2012 21:53
Show Gist options
  • Save jmikola/1811029 to your computer and use it in GitHub Desktop.
Save jmikola/1811029 to your computer and use it in GitHub Desktop.
MongoDB sorting orders for numeric integers and strings
[avocado: ~] $ mongo
MongoDB shell version: 2.0.2
connecting to: test
> db.foo.insert({x:10});
> db.foo.insert({x:"10"});
> db.foo.insert({x:5});
> db.foo.insert({x:"5"});
> db.foo.find().sort({x:-1});
{ "_id" : ObjectId("4f383479216ae77049825406"), "x" : "5" }
{ "_id" : ObjectId("4f383470216ae77049825404"), "x" : "10" }
{ "_id" : ObjectId("4f38346b216ae77049825403"), "x" : 10 }
{ "_id" : ObjectId("4f383475216ae77049825405"), "x" : 5 }
> db.foo.find().sort({x:1});
{ "_id" : ObjectId("4f383475216ae77049825405"), "x" : 5 }
{ "_id" : ObjectId("4f38346b216ae77049825403"), "x" : 10 }
{ "_id" : ObjectId("4f383470216ae77049825404"), "x" : "10" }
{ "_id" : ObjectId("4f383479216ae77049825406"), "x" : "5" }
>
@Heymancn
Copy link

did you solve this problem?

@unflores
Copy link

unflores commented Sep 30, 2016

I think there are two potential routes to take:

  1. try to make mongo sort by strings and integers
  2. only insert strings or integers and sort that way.

If all your data is of an integer form, just force the type. Just because the base is schemaless doesn't mean that you should let your data types be anything, and the more you let the types diverge, the more difficult it will be to do things with it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment