- The tests were performed in MongoDB v3.2.9.
- It does not matter what engine you're using in your MongoDB instance,
the space released of a removed document is not available to the system,
unless you execute specific commands, such
compact
(collection level) orrepairDatabase
(database level); - A collection must exist in order to execute the command
compact
;
Each engine have unique behaviors, I'll list what I've observed below.
- The space is only released to the system if the command
repairDatabase
is executed; - The space released of a dropped collection
is not
available to the system; - The space released from the command
compact
is not
released to the system;
- The space released of a dropped collection is a available to the system;
- The command
compact
releases spaces to the system, just likerepairDatabase
;
// g++ main.cpp -g3 -std=c++14 -I/usr/include/mongocxx/v_noabi -I/usr/include/bsoncxx/v_noabi -I/usr/include/libbson-1.0 -lbsoncxx -lmongocxx
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/builder/basic/kvp.hpp>
#include <iostream>
/**
* this code was written to test how mongo deals with disk space release
*/
int main (int argc, char** argv)
{
if (argc < 3)
{
std::cout << "[bin] [dbName] [collName]" << std::endl;
return 1;
}
try
{
std::string dbName(argv[1]);
std::string collName(argv[2]);
mongocxx::instance instance{};
mongocxx::client conn{ mongocxx::uri{} };
auto db = conn[dbName];
// remove all
auto removeFilter = bsoncxx::builder::basic::document{};
db[collName].delete_many(removeFilter.view());
// compact coll after remove
auto compactComm = bsoncxx::builder::basic::document{};
compactComm.append(bsoncxx::builder::basic::kvp("compact", collName));
db.run_command(compactComm.view());
// drop collection
db[collName].drop();
// repair database to release space
auto repairDbComm = bsoncxx::builder::basic::document{};
repairDbComm.append(bsoncxx::builder::basic::kvp("repairDatabase", 1));
db.run_command(repairDbComm.view());
}
catch (const std::exception& e)
{
std::cout << e.what() << std::endl;
}
}