Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb sort by date

Tags:

mongodb

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.
like image 576
Joey Avatar asked Apr 06 '16 04:04

Joey


People also ask

Does MongoDB support sorting?

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.

What is MongoDB default sort order?

by default mongo appears to return documents in insertion order. MongoDB returns documents in natural order when no sort order is specified.


2 Answers

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
like image 115
Sukanta Avatar answered Sep 19 '22 15:09

Sukanta


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

db.products.find().sort({"createdAt": 1}) 
like image 20
justusrk Avatar answered Sep 22 '22 15:09

justusrk