Để chuyển đổi collection hiện có thành Capped Collection (collection có kích thước cố định, tự động xóa tài liệu cũ khi đầy), sử dụng lệnh convertToCapped.
Tạo collection demo260 với 3 tài liệu:
> db.demo260.insertOne({"Name":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e47b1181627c0c63e7dba9b") }
> db.demo260.insertOne({"Name":"Bob"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e47b11c1627c0c63e7dba9c") }
> db.demo260.insertOne({"Name":"David"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e47b11f1627c0c63e7dba9d") }
Hiển thị dữ liệu:
> db.demo260.find();
Chuyển đổi thành capped collection với kích thước 8345 bytes:
> db.runCommand( { convertToCapped: 'demo260', size: 8345 } ); { "ok" : 1 }Kiểm tra trạng thái với
stats()- hiển thị "capped" : true và maxSize:> db.demo260.stats()Lưu ý: Capped collection không thể xóa tài liệu đơn lẻ, chỉ tự động xóa tài liệu cũ nhất khi vượt quá maxSize. Phù hợp cho log, cache, time-series data.