1MONGOC_DISTINCT_MAPREDUCE(3) MongoDB C Driver MONGOC_DISTINCT_MAPREDUCE(3)
2
3
4
6 mongoc_distinct_mapreduce - "distinct" and "mapReduce"
7
8 This document provides some practical, simple, examples to demonstrate
9 the distinct and mapReduce commands.
10
12 First we'll write some code to insert sample data: doc-com‐
13 mon-insert.c.INDENT 0.0
14
15 /* Don't try to compile this file on its own. It's meant to be #included
16 by example code */
17
18 /* Insert some sample data */
19 bool
20 insert_data (mongoc_collection_t *collection)
21 {
22 mongoc_bulk_operation_t *bulk;
23 enum N { ndocs = 4 };
24 bson_t *docs[ndocs];
25 bson_error_t error;
26 int i = 0;
27 bool ret;
28
29 bulk = mongoc_collection_create_bulk_operation_with_opts (collection, NULL);
30
31 docs[0] = BCON_NEW ("x", BCON_DOUBLE (1.0), "tags", "[", "dog", "cat", "]");
32 docs[1] = BCON_NEW ("x", BCON_DOUBLE (2.0), "tags", "[", "cat", "]");
33 docs[2] = BCON_NEW (
34 "x", BCON_DOUBLE (2.0), "tags", "[", "mouse", "cat", "dog", "]");
35 docs[3] = BCON_NEW ("x", BCON_DOUBLE (3.0), "tags", "[", "]");
36
37 for (i = 0; i < ndocs; i++) {
38 mongoc_bulk_operation_insert (bulk, docs[i]);
39 bson_destroy (docs[i]);
40 docs[i] = NULL;
41 }
42
43 ret = mongoc_bulk_operation_execute (bulk, NULL, &error);
44
45 if (!ret) {
46 fprintf (stderr, "Error inserting data: %s\n", error.message);
47 }
48
49 mongoc_bulk_operation_destroy (bulk);
50 return ret;
51 }
52
53 /* A helper which we'll use a lot later on */
54 void
55 print_res (const bson_t *reply)
56 {
57 char *str;
58 BSON_ASSERT (reply);
59 str = bson_as_canonical_extended_json (reply, NULL);
60 printf ("%s\n", str);
61 bson_free (str);
62 }
63
64
66 This is how to use the distinct command to get the distinct values of x
67 which are greater than 1: distinct.c.INDENT 0.0
68
69 bool
70 distinct (mongoc_database_t *database)
71 {
72 bson_t *command;
73 bson_t reply;
74 bson_error_t error;
75 bool res;
76 bson_iter_t iter;
77 bson_iter_t array_iter;
78 double val;
79
80 command = BCON_NEW ("distinct",
81 BCON_UTF8 (COLLECTION_NAME),
82 "key",
83 BCON_UTF8 ("x"),
84 "query",
85 "{",
86 "x",
87 "{",
88 "$gt",
89 BCON_DOUBLE (1.0),
90 "}",
91 "}");
92 res =
93 mongoc_database_command_simple (database, command, NULL, &reply, &error);
94 if (!res) {
95 fprintf (stderr, "Error with distinct: %s\n", error.message);
96 goto cleanup;
97 }
98
99 /* Do something with reply (in this case iterate through the values) */
100 if (!(bson_iter_init_find (&iter, &reply, "values") &&
101 BSON_ITER_HOLDS_ARRAY (&iter) &&
102 bson_iter_recurse (&iter, &array_iter))) {
103 fprintf (stderr, "Couldn't extract \"values\" field from response\n");
104 goto cleanup;
105 }
106
107 while (bson_iter_next (&array_iter)) {
108 if (BSON_ITER_HOLDS_DOUBLE (&array_iter)) {
109 val = bson_iter_double (&array_iter);
110 printf ("Next double: %f\n", val);
111 }
112 }
113
114 cleanup:
115 /* cleanup */
116 bson_destroy (command);
117 bson_destroy (&reply);
118 return res;
119 }
120
121
123 A simple example using the map reduce framework. It simply adds up the
124 number of occurrences of each "tag".
125
126 First define the map and reduce functions: constants.c.INDENT 0.0
127
128 const char *const COLLECTION_NAME = "things";
129
130 /* Our map function just emits a single (key, 1) pair for each tag
131 in the array: */
132 const char *const MAPPER = "function () {"
133 "this.tags.forEach(function(z) {"
134 "emit(z, 1);"
135 "});"
136 "}";
137
138 /* The reduce function sums over all of the emitted values for a
139 given key: */
140 const char *const REDUCER = "function (key, values) {"
141 "var total = 0;"
142 "for (var i = 0; i < values.length; i++) {"
143 "total += values[i];"
144 "}"
145 "return total;"
146 "}";
147 /* Note We can't just return values.length as the reduce function
148 might be called iteratively on the results of other reduce
149 steps. */
150
151
152Run the mapReduce command: map-reduce-basic.c.INDENT 0.0
153
154 bool
155 map_reduce_basic (mongoc_database_t *database)
156 {
157 bson_t reply;
158 bson_t *command;
159 bool res;
160 bson_error_t error;
161 mongoc_cursor_t *cursor;
162 const bson_t *doc;
163
164 bool query_done = false;
165
166 const char *out_collection_name = "outCollection";
167 mongoc_collection_t *out_collection;
168
169 /* Empty find query */
170 bson_t find_query = BSON_INITIALIZER;
171
172 /* Construct the mapReduce command */
173
174 /* Other arguments can also be specified here, like "query" or
175 "limit" and so on */
176 command = BCON_NEW ("mapReduce",
177 BCON_UTF8 (COLLECTION_NAME),
178 "map",
179 BCON_CODE (MAPPER),
180 "reduce",
181 BCON_CODE (REDUCER),
182 "out",
183 BCON_UTF8 (out_collection_name));
184 res =
185 mongoc_database_command_simple (database, command, NULL, &reply, &error);
186
187 if (!res) {
188 fprintf (stderr, "MapReduce failed: %s\n", error.message);
189 goto cleanup;
190 }
191
192 /* Do something with the reply (it doesn't contain the mapReduce results) */
193 print_res (&reply);
194
195 /* Now we'll query outCollection to see what the results are */
196 out_collection =
197 mongoc_database_get_collection (database, out_collection_name);
198 cursor = mongoc_collection_find_with_opts (
199 out_collection, &find_query, NULL, NULL);
200 query_done = true;
201
202 /* Do something with the results */
203 while (mongoc_cursor_next (cursor, &doc)) {
204 print_res (doc);
205 }
206
207 if (mongoc_cursor_error (cursor, &error)) {
208 fprintf (stderr, "ERROR: %s\n", error.message);
209 res = false;
210 goto cleanup;
211 }
212
213 cleanup:
214 /* cleanup */
215 if (query_done) {
216 mongoc_cursor_destroy (cursor);
217 mongoc_collection_destroy (out_collection);
218 }
219
220 bson_destroy (&reply);
221 bson_destroy (command);
222
223 return res;
224 }
225
226
228 You must have replica set running for this.
229
230 In this example we contact a secondary in the replica set and do an
231 "inline" map reduce, so the results are returned immediately:
232 map-reduce-advanced.c.INDENT 0.0
233
234 bool
235 map_reduce_advanced (mongoc_database_t *database)
236 {
237 bson_t *command;
238 bson_error_t error;
239 bool res = true;
240 mongoc_cursor_t *cursor;
241 mongoc_read_prefs_t *read_pref;
242 const bson_t *doc;
243
244 /* Construct the mapReduce command */
245 /* Other arguments can also be specified here, like "query" or "limit"
246 and so on */
247
248 /* Read the results inline from a secondary replica */
249 command = BCON_NEW ("mapReduce",
250 BCON_UTF8 (COLLECTION_NAME),
251 "map",
252 BCON_CODE (MAPPER),
253 "reduce",
254 BCON_CODE (REDUCER),
255 "out",
256 "{",
257 "inline",
258 "1",
259 "}");
260
261 read_pref = mongoc_read_prefs_new (MONGOC_READ_SECONDARY);
262 cursor = mongoc_database_command (
263 database, MONGOC_QUERY_NONE, 0, 0, 0, command, NULL, read_pref);
264
265 /* Do something with the results */
266 while (mongoc_cursor_next (cursor, &doc)) {
267 print_res (doc);
268 }
269
270 if (mongoc_cursor_error (cursor, &error)) {
271 fprintf (stderr, "ERROR: %s\n", error.message);
272 res = false;
273 }
274
275 mongoc_cursor_destroy (cursor);
276 mongoc_read_prefs_destroy (read_pref);
277 bson_destroy (command);
278
279 return res;
280 }
281
282
284 Here's how to run the example code basic-aggregation.c.INDENT 0.0
285
286 /*
287 * Copyright 2016 MongoDB, Inc.
288 *
289 * Licensed under the Apache License, Version 2.0 (the "License");
290 * you may not use this file except in compliance with the License.
291 * You may obtain a copy of the License at
292 *
293 * http://www.apache.org/licenses/LICENSE-2.0
294 *
295 * Unless required by applicable law or agreed to in writing, software
296 * distributed under the License is distributed on an "AS IS" BASIS,
297 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
298 * See the License for the specific language governing permissions and
299 * limitations under the License.
300 */
301
302
303 #include <mongoc/mongoc.h>
304 #include <stdio.h>
305
306
307 #include "constants.c"
308
309 #include "../doc-common-insert.c"
310 #include "distinct.c"
311 #include "map-reduce-basic.c"
312 #include "map-reduce-advanced.c"
313
314
315 int
316 main (int argc, char *argv[])
317 {
318 mongoc_database_t *database = NULL;
319 mongoc_client_t *client = NULL;
320 mongoc_collection_t *collection = NULL;
321 mongoc_uri_t *uri = NULL;
322 bson_error_t error;
323 char *host_and_port = NULL;
324 int exit_code = EXIT_FAILURE;
325
326 if (argc != 2) {
327 fprintf (stderr, "usage: %s CONNECTION-STRING\n", argv[0]);
328 fprintf (stderr,
329 "the connection string can be of the following forms:\n");
330 fprintf (stderr, "localhost\t\t\t\tlocal machine\n");
331 fprintf (stderr, "localhost:27018\t\t\t\tlocal machine on port 27018\n");
332 fprintf (stderr,
333 "mongodb://user:pass@localhost:27017\t"
334 "local machine on port 27017, and authenticate with username "
335 "user and password pass\n");
336 return exit_code;
337 }
338
339 mongoc_init ();
340
341 if (strncmp (argv[1], "mongodb://", 10) == 0) {
342 host_and_port = bson_strdup (argv[1]);
343 } else {
344 host_and_port = bson_strdup_printf ("mongodb://%s", argv[1]);
345 }
346
347 uri = mongoc_uri_new_with_error (host_and_port, &error);
348 if (!uri) {
349 fprintf (stderr,
350 "failed to parse URI: %s\n"
351 "error message: %s\n",
352 host_and_port,
353 error.message);
354 goto cleanup;
355 }
356
357 client = mongoc_client_new_from_uri (uri);
358 if (!client) {
359 goto cleanup;
360 }
361
362 mongoc_client_set_error_api (client, 2);
363 database = mongoc_client_get_database (client, "test");
364 collection = mongoc_database_get_collection (database, COLLECTION_NAME);
365
366 printf ("Inserting data\n");
367 if (!insert_data (collection)) {
368 goto cleanup;
369 }
370
371 printf ("distinct\n");
372 if (!distinct (database)) {
373 goto cleanup;
374 }
375
376 printf ("map reduce\n");
377 if (!map_reduce_basic (database)) {
378 goto cleanup;
379 }
380
381 printf ("more complicated map reduce\n");
382 if (!map_reduce_advanced (database)) {
383 goto cleanup;
384 }
385
386 exit_code = EXIT_SUCCESS;
387
388 cleanup:
389 if (collection) {
390 mongoc_collection_destroy (collection);
391 }
392
393 if (database) {
394 mongoc_database_destroy (database);
395 }
396
397 if (client) {
398 mongoc_client_destroy (client);
399 }
400
401 if (uri) {
402 mongoc_uri_destroy (uri);
403 }
404
405 if (host_and_port) {
406 bson_free (host_and_port);
407 }
408
409 mongoc_cleanup ();
410 return exit_code;
411 }
412
413
414If you want to try the advanced map reduce example with a secondary, start a
415replica set (instructions for how to do this can be found here).
416
417Otherwise, just start an instance of MongoDB:
418
419 $ mongod
420
421 Now compile and run the example program:
422
423 $ cd examples/basic_aggregation/
424 $ gcc -Wall -o agg-example basic-aggregation.c $(pkg-config --cflags --libs libmongoc-1.0)
425 $ ./agg-example localhost
426
427 Inserting data
428 distinct
429 Next double: 2.000000
430 Next double: 3.000000
431 map reduce
432 { "result" : "outCollection", "timeMillis" : 155, "counts" : { "input" : 84, "emit" : 126, "reduce" : 3, "output" : 3 }, "ok" : 1 }
433 { "_id" : "cat", "value" : 63 }
434 { "_id" : "dog", "value" : 42 }
435 { "_id" : "mouse", "value" : 21 }
436 more complicated map reduce
437 { "results" : [ { "_id" : "cat", "value" : 63 }, { "_id" : "dog", "value" : 42 }, { "_id" : "mouse", "value" : 21 } ], "timeMillis" : 14, "counts" : { "input" : 84, "emit" : 126, "reduce" : 3, "output" : 3 }, "ok" : 1 }
438
440 MongoDB, Inc
441
443 2017-present, MongoDB, Inc
444
445
446
447
4481.14.0 Feb 22, 2019 MONGOC_DISTINCT_MAPREDUCE(3)