有一个List ArrayList<Long> al=new ArrayList<Long>();里面存储了从外部获取的数据的ID并且进行了排序(随机抽取的ID,按照先后放入LIST),然后把这些ID在mongoDB通过inObj.put("_id", new BasicDBObject("$in", list));进行in查询,获取后的结果并不和LIST中ID的顺序一样,搜索了一下,有文章说不指定排序的话,mongodb会按照$natural进行排序,但是我测试了一下,并不是这样。
现在问题是怎么才能让mongodb按照list的排序获取结果呢
This is a great question. In fact, the article you checked is not wrong. If you don’t specify the order, it is arranged according to the natural order. It’s just that this natural sorting means to sort the data according to its own sorting method after finding the data within the range of
_id
的自然排序去排。你的list
只是一个查询条件,就相当于x > max AND x < min
指定的一个查询范围,跟排序完全没有关系,不论是什么数据库系统,都会在你指定的这个list
.My suggestion is that you still get the value in this way. After taking it out, loop it through the java program yourself, and then run out the sorted array.
@joyqi’s statement is not quite right. Natural sorting in MongoDB (that is, sorting by the $natural field) is different from sorting by the _id field. Natural sorting is based on the order in which data is organized in the data file.
You can explain your query and see how it uses the index. For example, if you use the following statement to insert data:
When you do not index the a field, you will get the following results. The following is the result of natural sorting:
Because MongoDB is a table query at this time, if a piece of data is scanned and meets the conditions, it is added to the return list. So it's done in natural order.
And if you add the index and check again, you will get the following results
You can see that the results are separated according to a being 1 and a being 2, because when querying by index, it is equivalent to checking multiple pieces of data in the index. In the example here, it is equivalent to checking that the range of a is [1,1] and [2,2], these two times are logically serial, first check the data of [1,1], and then check the data of [2,2], so here a is 1 and 2 's separated.
I have never used mongodb, but I feel that the answer to this question is the same as other relational databases. If you insert an ID like this in a relational database, and the ID is the primary key, the database will automatically sort according to the value of the ID, because the primary key itself is a clustered index. It is very simple to achieve the effect you want. Do not generate it yourself. ID, let Mongodb generate an automatically incrementing ID, so that the sorting is based on this auto-incrementing value when inserting, and when you read it, it is also read in the order of insertion.
Search and rank them!