-
Notifications
You must be signed in to change notification settings - Fork 2
/
hello_mongoc.c
96 lines (82 loc) · 2.34 KB
/
hello_mongoc.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include "URI.h"
#include <mongoc/mongoc.h>
int main(int argc, char const *argv[]) {
// your MongoDB URI connection string
const char *uri_string = MY_MONGODB_URI;
// MongoDB URI created from above string
mongoc_uri_t *uri;
// MongoDB Client, used to connect to the DB
mongoc_client_t *client;
// Command to be sent, and reply
bson_t *command, reply;
// Error management
bson_error_t error;
// Misc
char *str;
bool retval;
/*
* Required to initialize libmongoc's internals
*/
mongoc_init();
/*
* Optionally get MongoDB URI from command line
*/
if (argc > 1) {
uri_string = argv[1];
}
/*
* Safely create a MongoDB URI object from the given string
*/
uri = mongoc_uri_new_with_error(uri_string, &error);
if (!uri) {
fprintf(stderr,
"failed to parse URI: %s\n"
"error message: %s\n",
uri_string, error.message);
return EXIT_FAILURE;
}
/*
* Create a new client instance, here we use the uri we just built
*/
client = mongoc_client_new_from_uri(uri);
if (!client) {
return EXIT_FAILURE;
}
/*
* Register the application name so we can track it in the profile logs
* on the server. This can also be done from the URI (see other examples).
*/
mongoc_client_set_appname(client, "connect-example");
/*
* Do work. This example pings the database and prints the result as JSON
* BCON == BSON C Object Notation
*/
command = BCON_NEW("ping", BCON_INT32(1));
// we run above command on our DB, using the client. We get reply and error
// (if any)
retval = mongoc_client_command_simple(client, "admin", command, NULL, &reply,
&error);
// mongoc_client_command_simple returns false and sets error if there are
// invalid arguments or a server or network error.
if (!retval) {
printf("Error: %s\n", error.message);
return EXIT_FAILURE;
}
// if we're here, there's a JSON response
str = bson_as_json(&reply, NULL);
printf("%s\n", str);
printf("Pinged your deployment. You successfully connected to MongoDB!\n");
/*
* Clean up memory
*/
bson_destroy(&reply);
bson_destroy(command);
bson_free(str);
/*
* Release our handles and clean up libmongoc
*/
mongoc_uri_destroy(uri);
mongoc_client_destroy(client);
mongoc_cleanup();
return EXIT_SUCCESS;
}