Can I insert document to the front of the collection ? Or is there method like col.find().reverse()
that can reverse the sequence of the document set generated by col.find()
?
Asked
Active
Viewed 128 times
1 Answers
2
Unless you're worried about natural order, and in general you shouldn't be, ordering is done when you query. You should think about the documents as being stored without any specific order, but retrieved in an order you (optionally) specify (using .sort(...)
).
Indexing can be used, not to force an order or the documents, but to speed up ordering when returning query results (and filtering).
This is true for databases in general, not only mongodb / nosql.
So to address your question: the term "front" is not well-defined.
If you use sort()
on your query, to retrieve the documents in a specific order, you can reverse it using sort(field_to_sort_by, -1)
.

shx2
- 61,779
- 13
- 130
- 153
-
So what should I do if I want to get sorted `.find()` by `time` desc ? – CDT May 18 '13 at 08:19
-
See my updated answer. Also, there's a good detailed "tutorial" [here](http://stackoverflow.com/questions/4421207/mongodb-how-to-get-the-last-n-records). – shx2 May 18 '13 at 08:21
-
Sure it does. You can also pass the sort-clause as an argument to `find`. – shx2 May 18 '13 at 08:41