Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Sắp xếp theo timestamp giảm dần (descending) trong MongoDB

Sử dụng sort() với giá trị -1

Phương thức sort({ field: -1 }) sắp xếp giảm dần, 1 cho tăng dần. Áp dụng cho trường kiểu ISODate (timestamp).

Dữ liệu mẫu

> db.demo737.insertMany([
  { timestamp: new ISODate("2020-04-01") },
  { timestamp: new ISODate("2020-10-31") },
  { timestamp: new ISODate("2020-05-02") }
]);

Truy vấn sắp xếp giảm dần

> db.demo737.find().sort({ timestamp: -1 });

Kết quả

{ "_id": ObjectId("..."), "timestamp": ISODate("2020-10-31T00:00:00Z") }
{ "_id": ObjectId("..."), "timestamp": ISODate("2020-05-02T00:00:00Z") }
{ "_id": ObjectId("..."), "timestamp": ISODate("2020-04-01T00:00:00Z") }

Bản ghi mới nhất (tháng 10) lên đầu.