Mongodb sort by date

694    Asked by BenButler in Python , Asked on Jul 4, 2021

 I have a document with a field _id has type ObjectId, and a field created_at has type Date.

_id is of course increasing, and the value of created_at is current_date should be increasing.

So my question is :

  1. Is there any chance that 2 documents, A and B, A._id > B._id, but A.created_at < B>.

  2. How to keep created_at as precise as possible, so the order of created_at corresponds to _id.



Answered by Asistha pandey

To mongodb sort by date you can use order_by on documents collection like

In Rails

Product.order_by("created_at desc")
In Mongodb for example
db.products.find().sort({"created_at": 1}) --- 1 for asc and -1 for desc

Your Answer

Interviews

Parent Categories