2

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 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It appear that some of the variables used during construction are private and can't be modified outside the class. I ended up patching the C++ driver code.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.