1MONGOC_COMMON_TASK_EXAMPLES(3) MongoDB C Driver MONGOC_COMMON_TASK_EXAMPLES(3)
2
3
4
6 mongoc_common_task_examples - Common Tasks
7
8 Drivers for some other languages provide helper functions to perform
9 certain common tasks. In the C Driver we must explicitly build commands
10 to send to the server.
11
12 This snippet contains example code for the explain and copydb commands.
13
15 First we'll write some code to insert sample data: doc-com‐
16 mon-insert.c.INDENT 0.0
17
18 /* Don't try to compile this file on its own. It's meant to be #included
19 by example code */
20
21 /* Insert some sample data */
22 bool
23 insert_data (mongoc_collection_t *collection)
24 {
25 mongoc_bulk_operation_t *bulk;
26 enum N { ndocs = 4 };
27 bson_t *docs[ndocs];
28 bson_error_t error;
29 int i = 0;
30 bool ret;
31
32 bulk = mongoc_collection_create_bulk_operation_with_opts (collection, NULL);
33
34 docs[0] = BCON_NEW ("x", BCON_DOUBLE (1.0), "tags", "[", "dog", "cat", "]");
35 docs[1] = BCON_NEW ("x", BCON_DOUBLE (2.0), "tags", "[", "cat", "]");
36 docs[2] = BCON_NEW (
37 "x", BCON_DOUBLE (2.0), "tags", "[", "mouse", "cat", "dog", "]");
38 docs[3] = BCON_NEW ("x", BCON_DOUBLE (3.0), "tags", "[", "]");
39
40 for (i = 0; i < ndocs; i++) {
41 mongoc_bulk_operation_insert (bulk, docs[i]);
42 bson_destroy (docs[i]);
43 docs[i] = NULL;
44 }
45
46 ret = mongoc_bulk_operation_execute (bulk, NULL, &error);
47
48 if (!ret) {
49 fprintf (stderr, "Error inserting data: %s\n", error.message);
50 }
51
52 mongoc_bulk_operation_destroy (bulk);
53 return ret;
54 }
55
56 /* A helper which we'll use a lot later on */
57 void
58 print_res (const bson_t *reply)
59 {
60 char *str;
61 BSON_ASSERT (reply);
62 str = bson_as_canonical_extended_json (reply, NULL);
63 printf ("%s\n", str);
64 bson_free (str);
65 }
66
67
69 This is how to use the explain command in MongoDB 3.2+:
70 explain.c.INDENT 0.0
71
72 bool
73 explain (mongoc_collection_t *collection)
74 {
75 bson_t *command;
76 bson_t reply;
77 bson_error_t error;
78 bool res;
79
80 command = BCON_NEW ("explain",
81 "{",
82 "find",
83 BCON_UTF8 (COLLECTION_NAME),
84 "filter",
85 "{",
86 "x",
87 BCON_INT32 (1),
88 "}",
89 "}");
90 res = mongoc_collection_command_simple (
91 collection, command, NULL, &reply, &error);
92 if (!res) {
93 fprintf (stderr, "Error with explain: %s\n", error.message);
94 goto cleanup;
95 }
96
97 /* Do something with the reply */
98 print_res (&reply);
99
100 cleanup:
101 bson_destroy (&reply);
102 bson_destroy (command);
103 return res;
104 }
105
106
108 This example requires two instances of mongo to be running.
109
110 Here's how to use the copydb command to copy a database from another
111 instance of MongoDB: copydb.c.INDENT 0.0
112
113 bool
114 copydb (mongoc_client_t *client, const char *other_host_and_port)
115 {
116 mongoc_database_t *admindb;
117 bson_t *command;
118 bson_t reply;
119 bson_error_t error;
120 bool res;
121
122 BSON_ASSERT (other_host_and_port);
123 /* Must do this from the admin db */
124 admindb = mongoc_client_get_database (client, "admin");
125
126 command = BCON_NEW ("copydb",
127 BCON_INT32 (1),
128 "fromdb",
129 BCON_UTF8 ("test"),
130 "todb",
131 BCON_UTF8 ("test2"),
132
133 /* If you want from a different host */
134 "fromhost",
135 BCON_UTF8 (other_host_and_port));
136 res =
137 mongoc_database_command_simple (admindb, command, NULL, &reply, &error);
138 if (!res) {
139 fprintf (stderr, "Error with copydb: %s\n", error.message);
140 goto cleanup;
141 }
142
143 /* Do something with the reply */
144 print_res (&reply);
145
146 cleanup:
147 bson_destroy (&reply);
148 bson_destroy (command);
149 mongoc_database_destroy (admindb);
150
151 return res;
152 }
153
154
156 common-operations.c.INDENT 0.0
157
158 /*
159 * Copyright 2016 MongoDB, Inc.
160 *
161 * Licensed under the Apache License, Version 2.0 (the "License");
162 * you may not use this file except in compliance with the License.
163 * You may obtain a copy of the License at
164 *
165 * http://www.apache.org/licenses/LICENSE-2.0
166 *
167 * Unless required by applicable law or agreed to in writing, software
168 * distributed under the License is distributed on an "AS IS" BASIS,
169 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
170 * See the License for the specific language governing permissions and
171 * limitations under the License.
172 */
173
174
175 #include <mongoc/mongoc.h>
176 #include <stdio.h>
177
178
179 const char *COLLECTION_NAME = "things";
180
181 #include "../doc-common-insert.c"
182 #include "explain.c"
183 #include "copydb.c"
184
185
186 int
187 main (int argc, char *argv[])
188 {
189 mongoc_database_t *database = NULL;
190 mongoc_client_t *client = NULL;
191 mongoc_collection_t *collection = NULL;
192 mongoc_uri_t *uri = NULL;
193 bson_error_t error;
194 char *host_and_port;
195 int res = 0;
196 char *other_host_and_port = NULL;
197
198 if (argc < 2 || argc > 3) {
199 fprintf (stderr,
200 "usage: %s MONGOD-1-CONNECTION-STRING "
201 "[MONGOD-2-HOST-NAME:MONGOD-2-PORT]\n",
202 argv[0]);
203 fprintf (stderr,
204 "MONGOD-1-CONNECTION-STRING can be "
205 "of the following forms:\n");
206 fprintf (stderr, "localhost\t\t\t\tlocal machine\n");
207 fprintf (stderr, "localhost:27018\t\t\t\tlocal machine on port 27018\n");
208 fprintf (stderr,
209 "mongodb://user:pass@localhost:27017\t"
210 "local machine on port 27017, and authenticate with username "
211 "user and password pass\n");
212 return EXIT_FAILURE;
213 }
214
215 mongoc_init ();
216
217 if (strncmp (argv[1], "mongodb://", 10) == 0) {
218 host_and_port = bson_strdup (argv[1]);
219 } else {
220 host_and_port = bson_strdup_printf ("mongodb://%s", argv[1]);
221 }
222 other_host_and_port = argc > 2 ? argv[2] : NULL;
223
224 uri = mongoc_uri_new_with_error (host_and_port, &error);
225 if (!uri) {
226 fprintf (stderr,
227 "failed to parse URI: %s\n"
228 "error message: %s\n",
229 host_and_port,
230 error.message);
231 res = EXIT_FAILURE;
232 goto cleanup;
233 }
234
235 client = mongoc_client_new_from_uri (uri);
236 if (!client) {
237 res = EXIT_FAILURE;
238 goto cleanup;
239 }
240
241 mongoc_client_set_error_api (client, 2);
242 database = mongoc_client_get_database (client, "test");
243 collection = mongoc_database_get_collection (database, COLLECTION_NAME);
244
245 printf ("Inserting data\n");
246 if (!insert_data (collection)) {
247 res = EXIT_FAILURE;
248 goto cleanup;
249 }
250
251 printf ("explain\n");
252 if (!explain (collection)) {
253 res = EXIT_FAILURE;
254 goto cleanup;
255 }
256
257 if (other_host_and_port) {
258 printf ("copydb\n");
259 if (!copydb (client, other_host_and_port)) {
260 res = EXIT_FAILURE;
261 goto cleanup;
262 }
263 }
264
265 cleanup:
266 if (collection) {
267 mongoc_collection_destroy (collection);
268 }
269
270 if (database) {
271 mongoc_database_destroy (database);
272 }
273
274 if (client) {
275 mongoc_client_destroy (client);
276 }
277
278 if (uri) {
279 mongoc_uri_destroy (uri);
280 }
281
282 bson_free (host_and_port);
283 mongoc_cleanup ();
284 return res;
285 }
286
287
288First launch two separate instances of mongod (must be done from separate
289shells):
290
291 $ mongod
292
293 $ mkdir /tmp/db2
294 $ mongod --dbpath /tmp/db2 --port 27018 # second instance
295
296 Now compile and run the example program:
297
298 $ cd examples/common_operations/$ gcc -Wall -o example common-operations.c $(pkg-config --cflags --libs libmongoc-1.0)$ ./example localhost:27017 localhost:27018
299 Inserting data
300 explain
301 {
302 "executionStats" : {
303 "allPlansExecution" : [],
304 "executionStages" : {
305 "advanced" : 19,
306 "direction" : "forward" ,
307 "docsExamined" : 76,
308 "executionTimeMillisEstimate" : 0,
309 "filter" : {
310 "x" : {
311 "$eq" : 1
312 }
313 },
314 "invalidates" : 0,
315 "isEOF" : 1,
316 "nReturned" : 19,
317 "needTime" : 58,
318 "needYield" : 0,
319 "restoreState" : 0,
320 "saveState" : 0,
321 "stage" : "COLLSCAN" ,
322 "works" : 78
323 },
324 "executionSuccess" : true,
325 "executionTimeMillis" : 0,
326 "nReturned" : 19,
327 "totalDocsExamined" : 76,
328 "totalKeysExamined" : 0
329 },
330 "ok" : 1,
331 "queryPlanner" : {
332 "indexFilterSet" : false,
333 "namespace" : "test.things",
334 "parsedQuery" : {
335 "x" : {
336 "$eq" : 1
337 }
338 },
339 "plannerVersion" : 1,
340 "rejectedPlans" : [],
341 "winningPlan" : {
342 "direction" : "forward" ,
343 "filter" : {
344 "x" : {
345 "$eq" : 1
346 }
347 },
348 "stage" : "COLLSCAN"
349 }
350 },
351 "serverInfo" : {
352 "gitVersion" : "05552b562c7a0b3143a729aaa0838e558dc49b25" ,
353 "host" : "MacBook-Pro-57.local",
354 "port" : 27017,
355 "version" : "3.2.6"
356 }
357 }
358 copydb
359 { "ok" : 1 }
360
362 MongoDB, Inc
363
365 2017-present, MongoDB, Inc
366
367
368
369
3701.14.0 Feb 22, 2019 MONGOC_COMMON_TASK_EXAMPLES(3)