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

Lấy 10 document mới nhất MongoDB không thay đổi thứ tự

Để lấy N document mới nhất (theo thứ tự insert) mà không sắp xếp lại, sử dụng skip() với count().

Tạo collection 12 document

> db.demo500.insertOne({value:10});
> db.demo500.insertOne({value:1200});
> db.demo500.insertOne({value:19});
> db.demo500.insertOne({value:28});
> db.demo500.insertOne({value:50});
> db.demo500.insertOne({value:70});
> db.demo500.insertOne({value:100});
> db.demo500.insertOne({value:10});
> db.demo500.insertOne({value:98});
> db.demo500.insertOne({value:80});
> db.demo500.insertOne({value:75});
> db.demo500.insertOne({value:68});

Hiển thị tất cả (theo thứ tự insert)

> db.demo500.find();

Kết quả 12 document theo thứ tự chèn

Lấy 10 document mới nhất (bỏ 2 document đầu)

> db.demo500.find().skip(db.demo500.count() - 10);

Kết quả (document 3-12, giữ nguyên thứ tự):

value: 19, 28, 50, 70, 100, 10, 98, 80, 75, 68

Giải thích:

  • db.demo500.count(): Tổng số document (12)
  • count() - 10 = 2: Bỏ qua 2 document đầu
  • skip(2): Bỏ 2 document đầu tiên
  • Không dùng sort() → giữ nguyên thứ tự tự nhiên (insert order)

⚠️ Vấn đề hiệu năng:

  • count() quét toàn bộ collection (chậm trên data lớn)
  • skip() phải duyệt qua document bị bỏ qua (chậm khi skip lớn)

Cách tốt hơn (MongoDB 3.2+): Dùng $natural sort + limit:

// Lấy 10 document mới nhất (theo thứ tự tự nhiên ngược)
db.demo500.find().sort({$natural: -1}).limit(10)

// Hoặc nếu có trường createdAt/_id ObjectId (có timestamp):
db.demo500.find().sort({_id: -1}).limit(10)

Cách này dùng index, không cần count/skip, hiệu năng tốt hơn rất nhiều.