Skip to content

Commit

Permalink
Added code and README
Browse files Browse the repository at this point in the history
  • Loading branch information
dfreniche committed Mar 13, 2023
1 parent 5d4ca4c commit 0058ee5
Show file tree
Hide file tree
Showing 8 changed files with 574 additions and 0 deletions.
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Hello, MongoC

Some simple examples using the [MongoDB C driver](https://www.mongodb.com/docs/drivers/c/)

## Build and run

These examples are built using GCC on macOS, but they should compile anywhere that has a C compiler

- clone this repo
- create a file called `URI.h` that contains your MongoDB Connection String, with this content:
```c
// URI.h
#define MY_MONGODB_URI "mongodb+srv://<your connection string, including user + password>"
```
- Make the build script executable `chmod a+x build-all.sh`
- `./build-all.sh`
In macOS you need to install Xcode first (free on the Mac App Store)
73 changes: 73 additions & 0 deletions bcon.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// bcon.c
// https://mongoc.org/libmongoc/current/tutorial.html#using-bcon
#include <mongoc/mongoc.h>

// Creating the JSON doc:
/*
{
born : ISODate("1906-12-09"),
died : ISODate("1992-01-01"),
name : {
first : "Grace",
last : "Hopper"
},
languages : [ "MATH-MATIC", "FLOW-MATIC", "COBOL" ],
degrees: [ { degree: "BA", school: "Vassar" },
{ degree: "PhD", school: "Yale" } ]
}
*/

int main(int argc, char *argv[]) {
struct tm born = {0};
struct tm died = {0};
bson_t *document;
char *str;

born.tm_year = 6;
born.tm_mon = 11;
born.tm_mday = 9;

died.tm_year = 92;
died.tm_mon = 0;
died.tm_mday = 1;

// document = BCON_NEW("born", BCON_DATE_TIME(mktime(&born) * 1000),
// "died", BCON_DATE_TIME(mktime(&died) * 1000),
// "name", "{",
// "first", BCON_UTF8("Grace"),
// "last", BCON_UTF8("Hopper"),
// "}",
// "languages", "[",
// BCON_UTF8("MATH-MATIC"),
// BCON_UTF8("FLOW-MATIC"),
// BCON_UTF8("COBOL"),
// "]",
// "degrees", "[",
// "{", "degree", BCON_UTF8("BA"), "school",
// BCON_UTF8("Vassar"), "}",
// "{", "degree", BCON_UTF8("PhD"),"school",
// BCON_UTF8("Yale"), "}",
// "]");

document = BCON_NEW("born", BCON_DATE_TIME(mktime(&born) * 1000), "died",
BCON_DATE_TIME(mktime(&died) * 1000), "name", "{",
"first", BCON_UTF8("Grace"), "last", BCON_UTF8("Hopper"),
"}", "languages", "[", BCON_UTF8("MATH-MATIC"),
BCON_UTF8("FLOW-MATIC"), BCON_UTF8("COBOL"), "]",
"degrees", "[", "{", "degree", BCON_UTF8("BA"), "school",
BCON_UTF8("Vassar"), "}", "{", "degree", BCON_UTF8("PhD"),
"school", BCON_UTF8("Yale"), "}", "]");

/*
* Print the document as a JSON string.
*/
str = bson_as_canonical_extended_json(document, NULL);
printf("%s\n", str);
bson_free(str);

/*
* Clean up allocated bson documents.
*/
bson_destroy(document);
return 0;
}
30 changes: 30 additions & 0 deletions build-all.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#!/bin/bash

SOURCE_FILES="insert find bcon list_collections hello_mongoc delete"

mkdir output

echo COMPILING ALL EXAMPLES!

for file in $SOURCE_FILES
do

echo "Compiling $file"

gcc -o output/$file $file.c \
-I/usr/local/include/libbson-1.0 -I/usr/local/include/libmongoc-1.0 \
-lmongoc-1.0 -lbson-1.0 -Wdeprecated-declarations -w

done

echo RUNNING ALL EXAMPLES! 🚀

for file in $SOURCE_FILES
do

echo "Running $file"
echo "-------------"

./output/$file

done
103 changes: 103 additions & 0 deletions delete.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
// delete.c
#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;

// Error management
bson_error_t error;

mongoc_collection_t *collection;
char **collection_names;
unsigned i;

// Object id and BSON doc
bson_oid_t oid;
bson_t *doc;

char *str;

/*
* Required to initialize libmongoc's internals
*/
mongoc_init();

/*
* 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");

/*
* Get a handle on the database "db_name" and collection "coll_name"
*/
collection = mongoc_client_get_collection(client, "sample_mflix", "movies");

// Let's insert one document in this collection!
doc = bson_new();
bson_oid_init(&oid, NULL);
BSON_APPEND_OID(doc, "_id", &oid);
BSON_APPEND_UTF8(doc, "name", "My super new picture");

if (!mongoc_collection_insert_one(collection, doc, NULL, NULL, &error)) {
fprintf(stderr, "%s\n", error.message);
} else {
printf("Document inserted!");
/*
* Print the document as a JSON string.
*/
str = bson_as_canonical_extended_json(doc, NULL);
printf("%s\n", str);
bson_free(str);
}

bson_destroy(doc);

// Delete the inserted document!

doc = bson_new();
BSON_APPEND_OID(doc, "_id", &oid);

if (!mongoc_collection_delete_one(collection, doc, NULL, NULL, &error)) {
fprintf(stderr, "Delete failed: %s\n", error.message);
} else {
puts("Document deleted!");
}

/*
* Release our handles and clean up libmongoc
*/

mongoc_collection_destroy(collection);
mongoc_uri_destroy(uri);
mongoc_client_destroy(client);
mongoc_cleanup();

return EXIT_SUCCESS;
}
87 changes: 87 additions & 0 deletions find.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// find.c
#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;

// Error management
bson_error_t error;

mongoc_collection_t *collection;
char **collection_names;
unsigned i;

// Query object
bson_t *query;
mongoc_cursor_t *cursor;

char *str;

/*
* Required to initialize libmongoc's internals
*/
mongoc_init();

/*
* 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) {
puts("Error connecting!");
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");

/*
* Get a handle on the database "db_name" and collection "coll_name"
*/
collection = mongoc_client_get_collection(client, "sample_mflix", "movies");

query = bson_new();

// All movies from 1984!
BSON_APPEND_INT32(query, "year", 1984);
cursor = mongoc_collection_find_with_opts(collection, query, NULL, NULL);

while (mongoc_cursor_next(cursor, &query)) {
str = bson_as_canonical_extended_json(query, NULL);
printf("%s\n", str);
bson_free(str);
}

/*
* Release our handles and clean up libmongoc
*/

bson_destroy(query);

mongoc_collection_destroy(collection);
mongoc_uri_destroy(uri);
mongoc_client_destroy(client);
mongoc_cleanup();

return EXIT_SUCCESS;
}
Loading

0 comments on commit 0058ee5

Please sign in to comment.