Capped collections are fixed-size collections that insert, retrieve, and delete documents based on insertion order. A capped collection can support high-throughput operations. Capped collections work much like circular buffers in that once a collection fills its allocated space, it makes room for new documents by overwriting the oldest documents in the collection.
Capped collections can also be limited based on a maximum number of documents. This is useful for reducing the indexing overhead that can occur when storing large numbers of documents in a collection.
Capped collections are extremely useful for rotating event logs or caching data because you do not need to worry about expending the overhead and effort of implementing code in your application to clean up the collection.
To create a capped collection from the MongoDB shell, you use the createCollection()
method on the Db
object, specify the capped
property, and set the size, in bytes, as well as the optional maximum number of documents. For example:
db.createCollection("log", { capped : true, size : 5242880, max : 5000 } )
From the MongoDB Node.js native driver, you can also specify a capped collection in the db.createCollection()
method, described in Chapter 13. For example:
db.createCollection("newCollection", { capped : true, size : 5242880, max : 5000 }
function(err, collection){ });
From Mongoose you can define the collection as capped in the Schema
object options. For example:
var s = new Schema({ name:String, value:Number},
{ capped : true, size : 5242880, max : 5000});