0

Let's say I'm asking MongoDB for a query like this:

"someField" : {
        "$in" : [9,3,7,1]
    }

Will the returned objects be sorted by the order of the $in array?

IOW, when looking at the results, will I see all documents where {"someField" : 9} listed before the documents where {"someField":3 }, and then the 7's and then the 1's?

If not, any tips on how to get that?

Thanks!

Matthew Bonig
  • 2,001
  • 2
  • 20
  • 40
  • sure, I could.. but notice the order my id's are in.. it's not a natural order, so I can't just call .sort({someField:1}) because it would then return them in 1,3,7,9 order instead of what I want, which is the 9,3,7,1 order, same I supplied it as. I don't know how to write a .sort({"someField":[9,3,7,1]}) – Matthew Bonig Oct 31 '14 at 19:29
  • The question has been asked before, but it might have helped if you were pointed to a duplicate that actually shows a working solution, or several actually. Here: [Does MongoDB's $in clause guarantee order](http://stackoverflow.com/a/22800784/2313887) – Neil Lunn Nov 01 '14 at 00:35
  • hey everyone. Thanks... didn't realize this was a dupe, was sure I searched before. how I missed it I don't know. – Matthew Bonig Nov 01 '14 at 00:56

1 Answers1

0

Unfortunately, not only will the order of the $in array not affect the order of the results, but there also doesn't appear to be a built-in way to provide a custom sorting function to the sort function. You will mostly likely have to implement your own sorting function after retrieving the results. If you can tell us the language you're using to query MongoDB, we could probably help you with that part (if needed).

Troy Gizzi
  • 2,480
  • 1
  • 14
  • 15