Capped collections are fixed sized collections that have a very high performance auto-FIFO age-out feature (age out is based on insertion order). They are a bit like the "RRD" concept if you are familiar with that.
In addition, capped collections automatically, with high performance, maintain insertion order for the objects in the collection; this is very powerful for certain use cases such as logging.
Unlike a standard collection, you must explicitly create a capped collection, specifying a collection size in bytes. The collection's data space is then preallocated. Note that the size specified includes database headers.
> db.createCollection("mycoll", {capped:true, size:100000})
You may also optionally cap the number of objects in the collection. Once the limit is reached, items roll out on a least recently inserted basis.
To cap on number of objects, specify a max: parameter on the createCollection() call.
Note: When specifying a cap on the number of objects, you must also cap on size. Be sure to leave enough room for your chosen number of objects or items will roll out faster than expected. You can use the validate() utility method to see how much space an existing collection uses, and from that estimate your size needs.
Note: Capped collections are always capped by size and hence also limiting by number of documents is an overhead. Limiting by just size is faster.
db.createCollection("mycoll", {capped:true, size:100000, max:100}); db.mycoll.validate();
Tip: When programming, a handy way to store the most recently generated version of an object can be a collection capped with max=1.
The autoIndexId field may be set to true or false to explicitly enable or disable automatic creation of a unique key index on the _id object field. By default, such an index is is not created for capped collections.
An index is not automatically created on _id for capped collections by default |
If you will be using the _id field, you should create an index on _id.
The createCollection command may be used for non capped collections as well. For example:
db.createCollection("mycoll", {size:10000000}); db.createCollection("mycoll", {size:10000000, autoIndexId:false});
Explicitly creating a non capped collection via createCollection allows parameters of the new collection to be specified. For example, specification of a collection size causes the corresponding amount of disk space to be preallocated for use by the collection.
Capped collections are not shardable.
You can check if a collection is capped by using the isCapped() shell function. db.foo.isCapped()
You can convert a (non-capped) collection to a capped collection with the convertToCapped command:
> db.runCommand({"convertToCapped": "mycoll", size: 100000}); { "ok": 1 }
官方文档:http://www.mongodb.org/display/DOCS/Capped+Collections