Search code examples
ubuntumongo-c-driver

How to create a TTL index with Mongoc (mongo c lib)


I'm trying to add a TTL index in my mongodb with mongoc lib http://mongoc.org/.

What I'm doing is :

   keys = BCON_NEW("createdAt", BCON_INT32(1), "expireAfterSeconds", BCON_INT32(30));

   index_name = mongoc_collection_keys_to_index_string(keys);

   create_indexes = BCON_NEW("createIndexes", BCON_UTF8(COLLECTION_TEST), "indexes", "[", "{", "key", BCON_DOCUMENT(keys), "name", BCON_UTF8(index_name), "}", "]");

   mongoc_database_write_command_with_opts (database, create_indexes, NULL /* opts */, NULL, &error); 

The problem is that this code generate a json with this format :

{ "createdAt": 1 }, { "expireAfterSeconds": 3600 }

and I'm looking for a json with this format :

{ "createdAt": 1 }, { expireAfterSeconds: 3600 } // The expireAfterSeconds must not be inside a "".

Solution

  • I figured out :

    keys = BCON_NEW("expireAt", BCON_INT32(1));
    
    create_indexes = BCON_NEW ("createIndexes", BCON_UTF8 (COLLECTION_TEST), "indexes", "[", "{", "key", BCON_DOCUMENT (keys[0]), "expireAfterSeconds", BCON_INT32(0), "name", BCON_UTF8 (index_name[0]), "}", "]");