-1

When I insertOne() document in the collection Mongo add the document between the first and last document. It is expected to be added at the end, right? But for me ideally would be to add the document at the beginning, for example as .unshift() JS works. I'm building Blog so new posts should be added at the top of the list. But I can always .reverse() of course . Main problem is why document is added in the middle.

Community
  • 1
  • 1
Denis Lapadatovic
  • 305
  • 1
  • 9
  • 16

1 Answers1

2

You should sort the collection by creation time(when you are trying to output them sorted by creation time) rather than trying to change to order of insertions in the collections.

db.posts.find().sort({creation_time: -1})

This way the recent entries will come out on top.

Ref: https://docs.mongodb.com/manual/reference/method/cursor.sort/#cursor.sort

falloutx
  • 81
  • 1
  • 6
  • I have my `date` in this format **dd/mm/yyyy** i tried to sort it by its sorted just by first number `dd`. Doesn't consider whole string. Any way to fix this? – Denis Lapadatovic Oct 07 '17 at 11:33
  • You need to store date/time data as [mongodb Date()](https://docs.mongodb.com/manual/reference/method/Date/) and not as a string, this way the sorting will work correctly. If you still want to keep your dates as a string, then you'll have to write a custom sort function. – falloutx Oct 07 '17 at 15:39