Created
February 12, 2012 21:53
-
-
Save jmikola/1811029 to your computer and use it in GitHub Desktop.
MongoDB sorting orders for numeric integers and strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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" } | |
> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think there are two potential routes to take:
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.