Mongo uses $in to sort query results.

  mongodb, question

The recent project used mongo as a database and encountered a problem.


When using such a query, the results of the query are sorted naturally, that is:


{d, c, b, a}, not when passing values;
My guess is that the operation of $in is to traverse the data according to the natural order and compare it with the data in $in turn, so the final data will be sorted according to the natural order. However, the current business needs need to be sorted according to the order of value transfer. Is it only possible for the code layer to realize sorting?
I’m using PHP, and I don’t know if there is a simpler way to sort.
Please advise.

Just now, I saw another similar problem. If nodeID is indexed, I will query according to the value of $in. I’ll give it a try.

After the index is added, it is indeed sorted according to the incoming order, but some people have already said downstairs that this is a mongo feature and cannot be used as a dependency. Now it can only be implemented through the code layer.

I can guess why there is such a result:

  1. If there is no index, do soCOLLSCANYes, press$naturalOrder traversal, so out is also a natural sort;

  2. If there is an index, it will be done key by key.IXSCAN, and then one by one into the result set, that is, the order you want.

From a programming point of view, this is meaningful. However, there is no guarantee that future versions of MongoDB will always maintain such behavior.
In fact, most databases will return results in random order, that is, the order that the engine considers the most efficient, when ordering is not specified. So even if the most efficient order is exactly the one you want, it doesn’t mean it will always be the same. Don’t rely on this feature, otherwise there will be very strange and difficult to locate problems when a certain version is upgraded in the future.
Personal advice:

  1. If possible, specify the order according to the input order to get the correct result order.

  2. If the order entered cannot be specified, it will sort itself in the program.