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 :
A._id > B._id
, but A.created_at < B.created_at
.created_at
as precise as possible, so the order of created_at
corresponds to _id
.MongoDB can perform sort operations on a single-field index in ascending or descending order. In compound indexes, the sort order determines whether the index can be sorted. The sort keys must be listed in the same order as defined in the index.
by default mongo appears to return documents in insertion order. MongoDB returns documents in natural order when no sort order is specified.
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
Mongoose creates timestamps with field name "createdAt" and "updatedAt"
db.products.find().sort({"createdAt": 1})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With