How can I compact a collection in my IBM Cloud Databases for MongoDB deployment?

46 Views Asked by At

I have a deployment of IBM Cloud Databases for MongoDB. I want to compact the collections in my database to save disk space and increase performance. How can I achieve that?

1

There are 1 best solutions below

0
Daniel Mermelstein On

You can do this using the Mongo shell CLI.

To connect to your IBM Cloud Databases for MongoDB instances using the Mongo shell you will need:

  • The password for the admin user
  • The CA certificate, downloaded and stored locally as a file
  • A set of host names and ports

See the instructions on how to obtain these in the documentation

The connection string contains a list of the 3 nodes that make up your Highly Available cluster. You will need to target each node separately and compact the copy of the collection on every node.

To connect to a node, use the following Mongo shell command:

mongosh -u admin -p <your_password> --ssl --sslCAFile path/to/file  --authenticationDatabase admin --host <hostname:port>

# Current Mongosh Log ID:   xxxx
#Connecting to:     mongodb://<credentials>@hostname:port/?#directConnection=true&authSource=admin&tls=true&tlsCAFile=file&appName=mongosh+2.1.1
#For mongosh info see: https://docs.mongodb.com/mongodb-shell/
#Enterprise replset [direct: secondary] test>

Now target the database where your collection is:

use mydb

Finally, issue the compact command for each collection you want to compact:

db.runCommand({compact:"mycollection"})

Be aware that this command will fail if you try to compact a collection in the current Primary node. You may add a force flag to the command if you want to proceed regardless:

db.runCommand({compact:"catalog", force:true})

The MongoDB documentation suggest that this does not block CRUD operations while compacting.