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

Lấy tài liệu đầu và cuối hiệu quả trong MongoDB

Sử dụng aggregation $group với $first và $last để lấy tài liệu đầu/cuối. Tạo collection:

> db.demo73.insertOne({"Name":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e29c41b71bf0181ecc4226c") }
> db.demo73.insertOne({"Name":"Bob"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e29c41e71bf0181ecc4226d") }
> db.demo73.insertOne({"Name":"David"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e29c42271bf0181ecc4226e") }

Hiển thị theo thứ tự insert (mặc định):

> db.demo73.find();

Aggregation lấy first và last cùng lúc:

> db.demo73.aggregate({
   $group: {
      _id: null,
      first: { $first: "$$ROOT" },
      last: { $last: "$$ROOT" }
   }
});

Kết quả - Chris (đầu) và David (cuối):

Lưu ý quan trọng: Thứ tự "đầu/cuối" phụ thuộc vào thứ tự tài liệu vào pipeline. Mặc định là thứ tự tự nhiên (insert order). Để đảm bảo đúng, hãy thêm {$sort: {_id: 1}} trước $group. $$ROOT$$ tham chiếu toàn bộ document hiện tại.