May 17, 2021 MongoDB
1. MongoDB Fixed Collections (Capped Collections)
The MongoDB Fixed Collection (Capped Collections) is a well-performing, fixed-size collection that, for fixed size, can imagine being like a ring queue, with the element inserted over the initial head when the collection space is used up!
Let's create a fixed collection with creativeCollection, and the place option is set to true:
>db.createCollection("cappedLogCollection",{capped:true,size:10000})
You can also specify the number of documents, plus max:1000 properties:
>db.createCollection("cappedLogCollection",{capped:true,size:10000,max:1000})
To determine whether a collection is a fixed collection:
>db.cappedLogCollection.isCapped()
If you need to convert an existing collection to a fixed collection, you can use the following commands:
>db.runCommand({"convertToCapped":"posts",size:10000})
The above code converts the posts collection that we already have to a fixed collection.
Fixed collection documents are stored in the insert order, queries are returned in the insert order by default, or the return order can be adjusted using $natural.
>db.cappedLogCollection.find().sort({$natural:-1})
You can insert and update, but the update cannot exceed the size of the collection, otherwise the update fails and is not allowed to be deleted, but drop() can be called to delete all rows in the collection, but the collection needs to be explicitly rebuilt after drop.
The maximum value of a cappped collection on a 32-bit machine is about 482.5M, and the 64-bit is limited only by the system file size.