<page id="updating-document"
      type="topic"
      xmlns="http://projectmallard.org/1.0/">

  <info>
    <link type="guide" xref="tutorial#crud-operations"/>
  </info>

  <title>Updating a Document</title>
  <p>This code snippet gives an example of using <link xref="mongoc_collection_update">mongoc_collection_update()</link> to update the fields of a document.</p>
  <p>Using the "mydb" database, the following example inserts an example document into the "mycoll" collection. Then, using its <code>_id</code> field, the document is updated with different values and a new field.</p>

  <listing>
    <title><file>update.c</file></title>
    <synopsis><code mime="text/x-csrc"><![CDATA[#include <bcon.h>
#include <bson.h>
#include <mongoc.h>
#include <stdio.h>

int
main (int   argc,
      char *argv[])
{
    mongoc_collection_t *collection;
    mongoc_client_t *client;
    bson_error_t error;
    bson_oid_t oid;
    bson_t *doc = NULL;
    bson_t *update = NULL;
    bson_t *query = NULL;

    mongoc_init ();

    client = mongoc_client_new ("mongodb://localhost:27017/");
    collection = mongoc_client_get_collection (client, "mydb", "mycoll");

    bson_oid_init (&oid, NULL);
    doc = BCON_NEW ("_id", BCON_OID (&oid),
                    "key", BCON_UTF8 ("old_value"));

    if (!mongoc_collection_insert (collection, MONGOC_INSERT_NONE, doc, NULL, &error)) {
        printf ("%s\n", error.message);
        goto fail;
    }

    query = BCON_NEW ("_id", BCON_OID (&oid));
    update = BCON_NEW ("$set", "{",
                           "key", BCON_UTF8 ("new_value"),
                           "updated", BCON_BOOL (true),
                       "}");

    if (!mongoc_collection_update (collection, MONGOC_UPDATE_NONE, query, update, NULL, &error)) {
        printf ("%s\n", error.message);
        goto fail;
    }

fail:
    if (doc)
        bson_destroy (doc);
    if (query)
        bson_destroy (query);
    if (update)
        bson_destroy (update);

    mongoc_collection_destroy (collection);
    mongoc_client_destroy (client);
    mongoc_cleanup ();

    return 0;
}
]]></code></synopsis>
  </listing>

  <p>Compile the code and run it:</p>
  <screen><output style="prompt">$ gcc -o update update.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./update</output></screen>

  <p>On Windows:</p>
  <screen><output style="prompt">C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 update.c
C:\> update
{ "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }</output></screen>

  <p>To verify that the update succeeded, connect with the MongoDB shell.</p>
  <screen><output style="prompt">$ mongo
MongoDB shell version: 3.0.6
connecting to: test
> use mydb
switched to db mydb
> db.mycoll.find({"updated" : true})
{ "_id" : ObjectId("55ef549236fe322f9490e17b"), "updated" : true, "key" : "new_value" }
> </output></screen>
</page>
