libmongo-client  0.1.8
Inserting documents into MongoDB

Now that we know how to connect, it is time to take another step forward, and put something into our database.

We already learned how to build BSON objects in Building BSON objects, so lets put that knowledge together, and insert a document!

void
tut_sync_insert (void)
{

First, we define a couple of variables, a connection, and three documents:

mongo_sync_connection *conn;
bson *doc1, *doc2, *doc3;

Then we do our routine connect:

conn = mongo_sync_connect ("localhost", 27017, FALSE);
if (!conn)
{
perror ("mongo_sync_connect()");
exit (1);
}
mongo_sync_connection * mongo_sync_connect(const gchar *address, gint port, gboolean slaveok)
Synchronously connect to a MongoDB server.
Definition: mongo-sync.c:201

And then build a BSON object, as we've learned earlier:

doc1 = bson_build (BSON_TYPE_STRING, "hello", "world", -1,
BSON_TYPE_INT32, "the_final_answer", 42,
BSON_TYPE_BOOLEAN, "yes?", FALSE,
BSON_TYPE_INT32, "n", 1,
bson_finish (doc1);
gboolean bson_finish(bson *b)
Finish a BSON object.
Definition: bson.c:521
bson * bson_build(bson_type type, const gchar *name,...)
Build a BSON object in one go.
Definition: bson.c:448
@ BSON_TYPE_STRING
4byte length + NULL terminated string
Definition: bson.h:67
@ BSON_TYPE_NONE
Only used for errors.
Definition: bson.h:65
@ BSON_TYPE_INT32
4byte integer
Definition: bson.h:84
@ BSON_TYPE_BOOLEAN
1byte boolean value
Definition: bson.h:73

Now we have a connection, and we have a document, it's time to get dirty, and insert:

if (!mongo_sync_cmd_insert (conn, "tutorial.docs", doc1, NULL))
{
perror ("mongo_sync_cmd_insert()");
exit (1);
}
gboolean mongo_sync_cmd_insert(mongo_sync_connection *conn, const gchar *ns,...)
Send an insert command to MongoDB.
Definition: mongo-sync.c:943

One might wonder what that NULL is at the end of mongo_sync_cmd_insert()'s argument list: it's the sentinel. The value that marks the end of the documents we want to insert. It is needed, because the insert command can take any number of documents, and it will try to insert them in bulk.

Lets try that, and build two more documents:

doc2 = bson_build (BSON_TYPE_INT32, "n", 2,
BSON_TYPE_BOOLEAN, "yes?", FALSE,
BSON_TYPE_STRING, "hello", "dolly", -1,
bson_finish (doc2);
doc3 = bson_build (BSON_TYPE_INT32, "n", 3,
BSON_TYPE_STRING, "hello", "nurse", -1,
BSON_TYPE_BOOLEAN, "yes?", TRUE,
bson_finish (doc3);

Then we insert the two new documents into the same collection, at the same time:

if (!mongo_sync_cmd_insert (conn, "tutorial.docs", doc2, doc3, NULL))
{
perror ("mongo_sync_cmd_insert()");
exit (1);
}

And we're done! It's that straightforward. All we have left is cleaning up!

bson_free (doc3);
bson_free (doc2);
bson_free (doc1);
}
void bson_free(bson *b)
Free the memory associated with a BSON object.
Definition: bson.c:579
void mongo_sync_disconnect(mongo_sync_connection *conn)
Close and free a synchronous MongoDB connection.
Definition: mongo-sync.c:396