MongoDB tutoria...login
MongoDB tutorial
author:php.cn  update time:2022-04-21 17:49:03

MongoDB fixed collection


MongoDB Capped Collections are collections with excellent performance and a fixed size. For a fixed size, we can imagine it is like a circular queue. When the collection space is used up, the collection will be inserted again. The element will overwrite the initial head element!


Create a fixed collection

We create a fixed collection through createCollection, and the capped option is set to true:

>db.createCollection("cappedLogCollection",{capped:true,size:10000})

You can also specify the number of documents, plus max:1000 Attributes:

>db.createCollection("cappedLogCollection",{capped:true,size:10000,max:1000})

Determine whether the collection is a fixed collection:

>db.cappedLogCollection.isCapped()

If you need to convert an existing collection into a fixed collection, you can use the following command:

>db.runCommand({"convertToCapped":"posts",size:10000})

Above The code converts our existing posts collection into a fixed collection.


Fixed collection query

Fixed collection documents are stored in the order of insertion. By default, the query is returned in the order of insertion. You can also use $natural to adjust the return order.

>db.cappedLogCollection.find().sort({$natural:-1})

Functional features of fixed collections

Can be inserted and updated, but the update cannot exceed the size of the collection, otherwise the update fails and deletion is not allowed, but drop() can be called to delete the collection All rows in , but the collection needs to be rebuilt explicitly after the drop.

The maximum size of a capped collection on a 32-bit machine is about 482.5M. On a 64-bit machine, it is only limited by the system file size.


Fixed collection attributes and usage

Attributes

  • Attribute 1: Inserting fixed collections is extremely fast

  • Attribute 2: Query output in insertion order is extremely fast

  • Attribute 3: When inserting the latest data, the oldest data can be eliminated

Usage

  • Usage 1: Store log information

  • Usage 2: Cache a small number of documents

php.cn