hey, I’m storing some news in a collection where i need to fetch all of them at once and i need to sort them by time so that the latest is first. But I was trying to find a better solution than sorting them in the query. So i tried indexing them but i think the id index affects more the ordering of the data.
the field i want to sort by is: ```created_at: ISODate(‘2024-05-30T20:27:23.295Z’)`
If anyone knows a better solution. Thanks
Hello @Oussama_Majdouli, Welcome to the MongoDB community forum,
Let me list down the possibilities,
-
While MongoDB does not guarantee to preserve the insert order in the collection, The actual order can be affected by various factors such as updates, deletes, and internal storage mechanisms. You need to take the help of indexes.
-
You can take advantage of the default index
_id
, but there are some points you need to know as you can compare with your use-case:- The timestamp in the
_id
field is only precise to the second. - If your application requires millisecond precision for sorting, the
_id
field’s timestamp might not be sufficient.
- The timestamp in the
-
For accuracy, you can create an index on the
created_at
field with data-typeISODate
and it’s more efficient than the above approaches. -
Refer to the Tiemseries collection, might be relate with your use-case.
If the only problem in _id’s timestamps is the precision, seconds are enough for me. So what i understand is that i can use _id to order them by timestamp but either way i choose the order will not be always accurate due to internal mechanisms and external updates.
I will add some context, the order require only seconds to minutes precision.
this collection will not receive a lot of updates or deletes, and maybe an insert or two a day.
I also tried indexing with the ISODate but it looks like it’s overwritten by id ( i think )
I will need to order another with time also but this collection will receive more interactions ( Inserts, deletes) so maybe i will use two approach for these two cases.
QUESTION: how can I use _id to order them ?
THANKS FOR YOUR TIME
You can use { _id: 1 }
for ascending order, { _id: -1 }
for descending order. For more details refer to the sort.
I tried to create a descending index on _id but it’s impossible but i found that they use the index even if it’s 1 by default to sort so i just added the sort option on _id {“_id”: -1}.
Thank you for your guidance
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.