File: mongoc_inserting_document.page

package info (click to toggle)
libmongoc 1.4.2-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 6,824 kB
  • ctags: 4,501
  • sloc: ansic: 57,956; makefile: 717; python: 502; sh: 54
file content (71 lines) | stat: -rw-r--r-- 2,371 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<page id="inserting-document"
      type="topic"
      xmlns="http://projectmallard.org/1.0/">

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

  <title>Inserting a Document</title>
  <p>To insert documents into a collection, first obtain a handle to a <code xref="mongoc_collection_t">mongoc_collection_t</code> via a <code xref="mongoc_client_t">mongoc_client_t</code>. Then, use <code xref="mongoc_collection_insert">mongoc_collection_insert()</code> to add BSON documents to the collection. This example inserts into the database "mydb" and collection "mycoll".</p>
  <p>When finished, ensure that allocated structures are freed by using their respective destroy functions.</p>

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

int
main (int   argc,
      char *argv[])
{
    mongoc_client_t *client;
    mongoc_collection_t *collection;
    mongoc_cursor_t *cursor;
    bson_error_t error;
    bson_oid_t oid;
    bson_t *doc;

    mongoc_init ();

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

    doc = bson_new ();
    bson_oid_init (&oid, NULL);
    BSON_APPEND_OID (doc, "_id", &oid);
    BSON_APPEND_UTF8 (doc, "hello", "world");

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

    bson_destroy (doc);
    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 insert insert.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./insert</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 insert.c
C:\> insert</output></screen>

  <p>To verify that the insert 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()
{ "_id" : ObjectId("55ef43766cb5f36a3bae6ee4"), "hello" : "world" }
> </output></screen>
</page>