In this recipe, we will demonstrate the process to convert a normal collection to a capped collection.
Refer to the Single node installation of MongoDB recipe in Chapter 1, Installing and Starting the MongoDB Server, and start a single instance of Mongo. This is the only prerequisite for this recipe. Start a Mongo shell and connect to the started server.
test
database:> use test
for(i = 1 ; i <= 100 ; i++) { db.normalCollection.insert({'i': i, val :'Some Text Content'}) }
> db.normalCollection.find()
system.namespaces
collection as follows, and note the result document:> db.system.namespaces.find({name : 'test.normalCollection'})
> db.runCommand({convertToCapped : 'normalCollection', size : 100})
> db.normalCollection.find()
system.namespaces
collection, as follows, and note the result document:> db.system.namespaces.find({name : 'test.normalCollection'})
We created a normal collection with 100 documents and then tried to convert it to a capped collection with a size of 100 bytes. The command has the following JSON document passed to the runCommand
function:
{convertToCapped : <name of normal collection>, size: <size in bytes of the capped collection>}
This command creates a capped collection with the mentioned size, and loads the documents in the natural order from the normal collection to the target capped collection. If the size of the capped collection reaches the limit mentioned, the old documents are removed in the FIFO order, making space for new documents. Once this is done, the created capped collection is renamed. Executing a find
query on the capped collection confirms that not all 100 documents that were originally present in the normal collection are present in the capped collection. A query on the system.namespaces
collection, before and after the execution of the convertToCapped
command, shows the change in the collection attributes. Note that this operation acquires a global write lock, blocking all read and write operations in this database. Also, any indexes present on the original collection are not created on this capped collection-up conversion.
Oplog is an important collection used for replication in MongoDB and is a capped collection. For more information on replication and oplogs, refer to the Understanding and analyzing oplogs recipe in Chapter 4, Administration. In the Implementing triggers in MongoDB using oplog recipe, we will use this oplog to implement a feature similar to the after insert/update/delete trigger of a relational database.