Joey
Joey

Reputation: 1659

Mongodb sort by date

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.created_at.
  2. How to keep created_at as precise as possible, so the order of created_at corresponds to _id.

Upvotes: 19

Views: 74222

Answers (2)

Justus
Justus

Reputation: 11

Mongoose creates timestamps with field name "createdAt" and "updatedAt"

db.products.find().sort({"createdAt": 1}) 

Upvotes: 1

Sukanta
Sukanta

Reputation: 585

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

Upvotes: 38

Related Questions