1 // Copyright 2017 MongoDB Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /* -- sphinx-include-start -- */
16 #include <mongoc.h>
17
18 int
main(int argc,char * argv[])19 main (int argc, char *argv[])
20 {
21 const char *uri_str = "mongodb://localhost:27017";
22 mongoc_client_t *client;
23 mongoc_database_t *database;
24 mongoc_collection_t *collection;
25 bson_t *command, reply, *insert;
26 bson_error_t error;
27 char *str;
28 bool retval;
29
30 /*
31 * Required to initialize libmongoc's internals
32 */
33 mongoc_init ();
34
35 /*
36 * Optionally get MongoDB URI from command line
37 */
38 if (argc > 1) {
39 uri_str = argv[1];
40 }
41
42 /*
43 * Create a new client instance
44 */
45 client = mongoc_client_new (uri_str);
46
47 /*
48 * Register the application name so we can track it in the profile logs
49 * on the server. This can also be done from the URI (see other examples).
50 */
51 mongoc_client_set_appname (client, "connect-example");
52
53 /*
54 * Get a handle on the database "db_name" and collection "coll_name"
55 */
56 database = mongoc_client_get_database (client, "db_name");
57 collection = mongoc_client_get_collection (client, "db_name", "coll_name");
58
59 /*
60 * Do work. This example pings the database, prints the result as JSON and
61 * performs an insert
62 */
63 command = BCON_NEW ("ping", BCON_INT32 (1));
64
65 retval = mongoc_client_command_simple (
66 client, "admin", command, NULL, &reply, &error);
67
68 if (!retval) {
69 fprintf (stderr, "%s\n", error.message);
70 return EXIT_FAILURE;
71 }
72
73 str = bson_as_json (&reply, NULL);
74 printf ("%s\n", str);
75
76 insert = BCON_NEW ("hello", BCON_UTF8 ("world"));
77
78 if (!mongoc_collection_insert (
79 collection, MONGOC_INSERT_NONE, insert, NULL, &error)) {
80 fprintf (stderr, "%s\n", error.message);
81 }
82
83 bson_destroy (insert);
84 bson_destroy (&reply);
85 bson_destroy (command);
86 bson_free (str);
87
88 /*
89 * Release our handles and clean up libmongoc
90 */
91 mongoc_collection_destroy (collection);
92 mongoc_database_destroy (database);
93 mongoc_client_destroy (client);
94 mongoc_cleanup ();
95
96 return 0;
97 }
98