Skip to content

Instantly share code, notes, and snippets.

@outcoldman
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save outcoldman/48369bff9347fb61a739 to your computer and use it in GitHub Desktop.
Save outcoldman/48369bff9347fb61a739 to your computer and use it in GitHub Desktop.
Mongo build insert (C Driver)
/* gcc example.c -o example $(pkg-config --cflags --libs libmongoc-1.0) */
/* ./example-client [CONNECTION_STRING [COLLECTION_NAME]] */
#include <mongoc.h>
#include <stdio.h>
#include <stdlib.h>
int
main (int argc,
char *argv[])
{
mongoc_uri_t* uri;
mongoc_client_pool_t* pool;
mongoc_client_t *client;
mongoc_collection_t *collection = NULL;
mongoc_cursor_t *cursor;
bson_error_t error;
bson_oid_t oid;
bson_t b;
const bson_t *doc;
const char *uristr = "mongodb://127.0.0.1/?w=0";
const char *collection_name = "test";
bson_t query;
char *str;
int tries = 0;
const bson_t *collectionerror;
bson_t* conf;
bson_t* members;
bson_t* m1;
bson_t* m2;
bson_t* m3;
bson_t* m4;
char *path1;
char *path2;
char *path3;
mongoc_bulk_operation_t* bulk;
mongoc_init ();
uri = mongoc_uri_new(uristr);
pool = mongoc_client_pool_new(uri);
client = mongoc_client_pool_pop (pool);
collection = mongoc_client_get_collection (client, "mydb", collection_name);
bulk = mongoc_collection_create_bulk_operation(collection, true, NULL);
tries = 1;
while(tries <= 1000000) {
bson_init(&b);
bson_oid_init(&oid, NULL);
bson_append_oid(&b, "_id", 3, &oid);
path1 = bson_strdup_printf ("String %d", tries + 0 );
path2 = bson_strdup_printf ("String %d", tries + 1 );
path3 = bson_strdup_printf ("String %d", tries + 2 );
m1 = bson_new();
BSON_APPEND_INT32(m1, "_id", tries + 0);
BSON_APPEND_UTF8(m1, "host", path1);
m2 = bson_new();
BSON_APPEND_INT32(m2, "_id", tries + 1);
BSON_APPEND_UTF8(m2, "host", path2);
m3 = bson_new();
BSON_APPEND_INT32(m3, "_id", tries + 2);
BSON_APPEND_UTF8(m3, "host", path3);
members = bson_new();
BSON_APPEND_DOCUMENT(members, "0", m1);
BSON_APPEND_DOCUMENT(members, "1", m2);
BSON_APPEND_DOCUMENT(members, "2", m3);
BSON_APPEND_ARRAY(&b, "members", members);
BSON_APPEND_INT32(&b, "version", tries);
mongoc_bulk_operation_insert(bulk, &b);
bson_free (path1);
bson_free (path2);
bson_free (path3);
bson_destroy(m1);
bson_destroy(m2);
bson_destroy(m3);
bson_destroy(members);
bson_destroy(&b);
tries++;
}
if (!mongoc_bulk_operation_execute(bulk, NULL, &error)) {
fprintf (stderr, "Collection insert Failure: %s, %d, %d\n", error.message, error.domain, error.code);
}
mongoc_bulk_operation_destroy(bulk);
mongoc_client_pool_destroy(pool);
mongoc_uri_destroy(uri);
mongoc_cleanup ();
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment