1 #include <mongo.h>
2
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <errno.h>
6 #include <string.h>
7
8 static void
do_inserts(mongo_sync_connection * conn)9 do_inserts (mongo_sync_connection *conn)
10 {
11 bson *base;
12 gint i;
13
14 base = bson_build
15 (BSON_TYPE_STRING, "tutorial-program", "tut_hl_client.c", -1,
16 BSON_TYPE_INT32, "the answer to life, the universe and everything", 42,
17 BSON_TYPE_NONE);
18 bson_finish (base);
19
20 for (i = 0; i < 1000; i++)
21 {
22 bson *n;
23
24 n = bson_new_from_data (bson_data (base), bson_size (base) - 1);
25 bson_append_int32 (n, "counter", i);
26 bson_finish (n);
27
28 if (!mongo_sync_cmd_insert (conn, "lmc.tutorial", n, NULL))
29 {
30 fprintf (stderr, "Error inserting document %d: %s\n", i,
31 strerror (errno));
32 exit (1);
33 }
34 bson_free (n);
35 }
36 bson_free (base);
37 }
38
39 static void
do_query(mongo_sync_connection * conn)40 do_query (mongo_sync_connection *conn)
41 {
42 mongo_sync_cursor *c;
43 bson *query;
44 gchar *error = NULL;
45
46 query = bson_build
47 (BSON_TYPE_STRING, "tutorial-program", "tut_hl_client.c", -1,
48 BSON_TYPE_NONE);
49 bson_finish (query);
50
51 c = mongo_sync_cursor_new (conn, "lmc.tutorial",
52 mongo_sync_cmd_query (conn, "lmc.tutorial", 0,
53 0, 10, query, NULL));
54 if (!c)
55 {
56 fprintf (stderr, "Error creating the query cursor: %s\n",
57 strerror (errno));
58 exit (1);
59 }
60 bson_free (query);
61
62 while (mongo_sync_cursor_next (c))
63 {
64 bson *b = mongo_sync_cursor_get_data (c);
65 bson_cursor *bc;
66 gint32 cnt;
67
68 if (!b)
69 {
70 int e = errno;
71
72 mongo_sync_cmd_get_last_error (conn, "lmc", &error);
73 fprintf (stderr, "Error retrieving cursor data: %s\n",
74 (error) ? error : strerror (e));
75 exit (1);
76 }
77
78 bc = bson_find (b, "counter");
79 bson_cursor_get_int32 (bc, &cnt);
80 printf ("\rCounter: %d", cnt);
81
82 bson_cursor_free (bc);
83 bson_free (b);
84 }
85 printf ("\n");
86
87 mongo_sync_cursor_free (c);
88 }
89
90 int
main(void)91 main (void)
92 {
93 mongo_sync_connection *conn;
94
95 conn = mongo_sync_connect ("localhost", 27017, FALSE);
96 if (!conn)
97 {
98 fprintf (stderr, "Connection failed: %s\n", strerror (errno));
99 return 1;
100 }
101
102 do_inserts (conn);
103 do_query (conn);
104
105 mongo_sync_disconnect (conn);
106 return 0;
107 }
108