最近的项目使用mongo作为数据库,遇到了一个问题。
db.col_content.find({'nodeID':{$in:[d,c,b,a]}})
使用这样的查询的时候,查询的结果是按照自然排序的,即:
{a.....},
{b.....},
{c.....},
{d.....},
不是在传值的时候的{d,c,b,a};
我的猜测是,$in的操作是按照自然排序遍历数据,依次跟$in里面的数据进行比较,所以才会最终的数据按照自然排序,但是现在的业务需求需要按照传值的顺序,难道只能代码层实现排序了吗?
我用的是PHP,不知道有没有比较简单的方法来进行排序。
请指教。
刚才看到另外一个类似的问题,如果有在nodeID上加索引的话,就会根据$in的传值进行查询。我去试一试。
加了索引之后确实按照传入顺序进行排序了,但是楼下已经有人说了,这个是mongo的特性,不能作为依赖,现在只能通过代码层来实现了。
巴扎黑2017-05-02 09:20:43
I can guess why there is such a result:
If there is no index, then COLLSCAN
是按$natural
sequential traversal is done, so what comes out is also naturally sorted;
If there is an index, it will be done IXSCAN
key by key, and then put into the result set one by one, which is the order you want.
From a programming perspective, this makes sense. But there is no guarantee that future versions of MongoDB will maintain this behavior.
In fact, most databases will return results in a random order when the sorting is not specified, which is the order that the engine thinks is the most efficient. So even if the most efficient order now is exactly the order you want, it doesn't mean it will always be that way in the future. Do not rely on this feature, otherwise very strange and difficult-to-locate problems will occur when a certain version is upgraded in the future.
Personal suggestion:
If possible, specify the sorting order according to the input order to get the correct result order.
If the order of input cannot be specified, sort it yourself in the program.