Skip to content

Instantly share code, notes, and snippets.

@sindbach
Created September 24, 2015 23:13
Show Gist options
  • Save sindbach/d6b31903f578fb2eb7ae to your computer and use it in GitHub Desktop.
Save sindbach/d6b31903f578fb2eb7ae to your computer and use it in GitHub Desktop.
A simple cpp example to uncap a capped collection in MongoDB. This version is using the legacy mongo-cxx-driver https://github.com/mongodb/mongo-cxx-driver.
#include "mongo/client/dbclient.h"
int main() {
/* Initialize Driver */
mongo::Status status = mongo::client::initialize();
if (!status.isOK()){
std::cout<< "Failed to initialize driver." << std::endl;
return EXIT_FAILURE;
}
/* Establish db connection */
mongo::DBClientConnection c;
try {
c.connect("localhost");
} catch( const mongo::DBException &e ) {
std::cout << "caught " << e.what() << std::endl;
}
/* The database name is 'capped' and the capped collection name is 'test',
using a temporary collection in the same database with a name 'temp'.
*/
const std::string CAPPED_COLL = "capped.test";
const std::string UNCAPPED_COLL = "capped.temp";
/* Copy collection from capped to uncapped collection */
std::auto_ptr<mongo::DBClientCursor> cursor = c.query(CAPPED_COLL, mongo::BSONObj());
while(cursor->more()){
mongo::BSONObj p = cursor->next();
c.insert(UNCAPPED_COLL, p);
}
/* Drop capped collection, and rename uncapped to capped collection */
mongo::BSONObj result;
c.runCommand("admin",
BSON("renameCollection"<<UNCAPPED_COLL
<<"to"<<CAPPED_COLL
<<"dropTarget"<<true),
result);
std::cout<< "Completed" <<std::endl;
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment