MongoDb creating sparse index using c++ driver

773 Views Asked by At

Is there a way to create a sparse index using the MongoDb (2.2) C++ driver?

It seems that the ensureIndex function does not accept this argument. From MongoDb docs:

bool mongo::DBClientWithCommands::ensureIndex(  
                          const string &    ns,
                          BSONObj   keys,
                          bool  unique = false,
                          const string &    name = "",
                          bool  cache = true,
                          bool  background = false,
                          int   v = -1) 
2

There are 2 best solutions below

0
On BEST ANSWER

I ended up patching the Mongo source code (mongo/cleint/dbclient.cpp):

bool DBClientWithCommands::ensureIndex( const string &ns , BSONObj keys , bool unique, const string & name , bool cache, bool background, int version, bool sparse ) {
    BSONObjBuilder toSave;
    toSave.append( "ns" , ns );
    toSave.append( "key" , keys );

    string cacheKey(ns);
    cacheKey += "--";

    if ( name != "" ) {
        toSave.append( "name" , name );
        cacheKey += name;
    }
    else {
        string nn = genIndexName( keys );
        toSave.append( "name" , nn );
        cacheKey += nn;
    }

    if( version >= 0 )
        toSave.append("v", version);

    if ( unique )
        toSave.appendBool( "unique", unique );

    if ( sparse )
        toSave.appendBool( "sparse", true );

    if( background )
        toSave.appendBool( "background", true );

    if ( _seenIndexes.count( cacheKey ) )
        return 0;

    if ( cache )
        _seenIndexes.insert( cacheKey );

    insert( Namespace( ns.c_str() ).getSisterNS( "system.indexes"  ).c_str() , toSave.obj() );
    return 1;
}

The issue should be resolved in version 2.3.2

1
On

For that matter, dropDups isn't an argument either...

As a workaround, you can build the server command yourself and append the sparse argument. If you follow this link, you'll notice that the server command consists of building a BSONObject and the various index options are appended as fields. It should be straightforward to write your own version of ensureIndex.