1 #include <mongoc.h>
2 #include <stdio.h>
3
4 static void
print_pipeline(mongoc_collection_t * collection)5 print_pipeline (mongoc_collection_t *collection)
6 {
7 mongoc_cursor_t *cursor;
8 bson_error_t error;
9 const bson_t *doc;
10 bson_t *pipeline;
11 char *str;
12
13 pipeline = BCON_NEW ("pipeline",
14 "[",
15 "{",
16 "$group",
17 "{",
18 "_id",
19 "$state",
20 "total_pop",
21 "{",
22 "$sum",
23 "$pop",
24 "}",
25 "}",
26 "}",
27 "{",
28 "$match",
29 "{",
30 "total_pop",
31 "{",
32 "$gte",
33 BCON_INT32 (10000000),
34 "}",
35 "}",
36 "}",
37 "]");
38
39 cursor = mongoc_collection_aggregate (
40 collection, MONGOC_QUERY_NONE, pipeline, NULL, NULL);
41
42 while (mongoc_cursor_next (cursor, &doc)) {
43 str = bson_as_canonical_extended_json (doc, NULL);
44 printf ("%s\n", str);
45 bson_free (str);
46 }
47
48 if (mongoc_cursor_error (cursor, &error)) {
49 fprintf (stderr, "Cursor Failure: %s\n", error.message);
50 }
51
52 mongoc_cursor_destroy (cursor);
53 bson_destroy (pipeline);
54 }
55
56 int
main(int argc,char * argv[])57 main (int argc, char *argv[])
58 {
59 mongoc_client_t *client;
60 mongoc_collection_t *collection;
61
62 mongoc_init ();
63
64 client = mongoc_client_new (
65 "mongodb://localhost:27017?appname=aggregation-example");
66 mongoc_client_set_error_api (client, 2);
67 collection = mongoc_client_get_collection (client, "test", "zipcodes");
68
69 print_pipeline (collection);
70
71 mongoc_collection_destroy (collection);
72 mongoc_client_destroy (client);
73
74 mongoc_cleanup ();
75
76 return 0;
77 }
78