Modifying collection behavior using the collMod command

This is a command that would be executed to change the behavior of a collection in mongo. It could be thought of as a collection modify operation (officially, it is not mentioned anywhere though).

For a part of this recipe, knowledge of TTL indexes is required.

Getting ready

In this recipe, we will execute the collMod operation on a collection. We need to start a standalone server listening to any port for client connections; in this case, we will stick to the default 27017. If you are not aware how to start a standalone server, refer to Installing single node MongoDB in Chapter 1, Installing and Starting the Server. We also need to start a shell that would be used for this administration. It is highly recommended to take a look at the recipes Expiring documents after a fixed interval using the TTL index and Expiring documents at a given time using the TTL index in Chapter 2, Command-line Operations and Indexes if you are not aware of them.

How it works…

This operation can be used to do a couple of things:

  1. Assuming we have a collection with TTL index, as we saw in Chapter 2, Command-line Operations, let us see the list indexes by executing the following:
    > db.ttlTest.getIndexes()
    
  2. To change the expiry to 800 ms from 300 ms, execute the following:
    > db.runCommand({collMod: 'ttlTest', index: {keyPattern: {createDate:1}, expireAfterSeconds:800}})
    

How it works…

The collMod command always has the following format: {collMod : <name of the collection>, <collmod operation>}.

We use the index operation using collMod to modify the TTL index. If a TTL index is already created and the time to live needs to be changed after creation, we use the collMod command. This operation-specific field to the command is as follows:

{index: {keyPattern: <the field on which the index was originally created>, expireAfterSeconds:<new time to be used for TTL of the index>}}

The keyPattern is the field, of the collection, on which the TTL index is created and the expireAfterSeconds will contain the new time to be changed to. On successful execution, we should see the following in the shell:

{ "expireAfterSeconds_old" : 300, "expireAfterSeconds_new" : 800, "ok" : 1 }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset