wshcdr
wshcdr

Reputation: 967

Create index with mongodb C Driver

I can create index in mongodb via mongodb shell

i.e. db['test'].ensureIndex( { fieldname:1 } )

But how to create the same index with mongo-c-driver? Who could point me out? thanks a lot!

Upvotes: 0

Views: 463

Answers (1)

CodePhobia
CodePhobia

Reputation: 1315

If you have a set of documents with keys as name and age

You can create indices like this:

static void tutorial_index( mongo_connection *conn ) {
  bson key[1];

  bson_init( key );
  bson_append_int( key, "name", 1 );
  bson_finish( key );

  mongo_create_index( conn, "tutorial.persons", key, 0, NULL );

  bson_destroy( key );

  printf( "simple index created on \"name\"\n" );

  bson_init( key );
  bson_append_int( key, "age", 1 );
  bson_append_int( key, "name", 1 );
  bson_finish( key );

  mongo_create_index( conn, "tutorial.persons", key, 0, NULL );

  bson_destroy( key );

  printf( "compound index created on \"age\", \"name\"\n" );
}

Reference: MongoDB Reference

Upvotes: 1

Related Questions