diff --git a/README.md b/README.md index 3d2ec16..f70df2f 100644 --- a/README.md +++ b/README.md @@ -6,10 +6,16 @@ includes its own setup instructions. ## Available Client Libraries +- [C](c/hello-world/README.md) +- [C++](cpp/hello-world/README.md) - [.NET/C#](dotnet/hello-world/README.md) - [Go](go/hello-world/README.md) -- [Java](java/hello-world/README.md) +- [Java Reactive Streams](java-rs/hello-world/README.md) +- [Java Sync](java/hello-world/README.md) +- [Kotlin Coroutines](kotlin-coroutine/hello-world/README.md) +- [Kotlin Sync](kotlin-sync/hello-world/README.md) - [Node.js](node/hello-world/README.md) +- [PHP](php/hello-world/README.md) - [Python](python/hello-world/README.md) ## Prerequisites diff --git a/c/hello-world/.gitignore b/c/hello-world/.gitignore new file mode 100644 index 0000000..567609b --- /dev/null +++ b/c/hello-world/.gitignore @@ -0,0 +1 @@ +build/ diff --git a/c/hello-world/CMakeLists.txt b/c/hello-world/CMakeLists.txt new file mode 100644 index 0000000..2d0f3b6 --- /dev/null +++ b/c/hello-world/CMakeLists.txt @@ -0,0 +1,10 @@ +cmake_minimum_required(VERSION 3.15) +project(hello-world C) + +set(CMAKE_C_STANDARD 11) +set(CMAKE_C_STANDARD_REQUIRED ON) + +find_package(mongoc 2.0 REQUIRED) + +add_executable(hello-world hello-world.c) +target_link_libraries(hello-world PRIVATE mongoc::mongoc) diff --git a/c/hello-world/README.md b/c/hello-world/README.md new file mode 100644 index 0000000..e597a51 --- /dev/null +++ b/c/hello-world/README.md @@ -0,0 +1,124 @@ +# Get Started with the MongoDB C Driver + +This sample application connects to a MongoDB deployment, seeds a small +set of sample product documents, and retrieves one of them. Because the +app inserts its own data, you don't need to load an external dataset. + +## Prerequisites + +Before you begin, complete the [Atlas Get Started guide](https://www.mongodb.com/docs/get-started/) +to create a free Atlas deployment and save your database user +credentials. + +You also need the following components installed in your development environment: + +- CMake 3.15 or later +- A C11-compatible compiler +- [vcpkg](https://github.com/microsoft/vcpkg) (Windows and Linux) + +The commands in this guide assume a Bash compatible shell. + +## Installation + +Clone this repository: + +```bash +git clone https://github.com/mongodb/docs-get-started +``` + +### Install the MongoDB C Driver + +This project requires MongoDB C driver 2.0 or later. Install it with your +platform's package manager. + +
+macOS / Linux + +On macOS, install the MongoDB C driver with [Homebrew](https://brew.sh/): + +```bash +brew install mongo-c-driver +``` + +On Linux, most distribution packages are too old to satisfy this +requirement. Use vcpkg instead: + +```bash +vcpkg install mongo-c-driver +``` + +Navigate into the project directory, then configure and build: + +```bash +cd docs-get-started/c/hello-world +cmake -S . -B build +cmake --build build +``` + +If you installed the driver with vcpkg, add the vcpkg toolchain file to +the configure step so CMake can locate it, replacing `` with +your vcpkg installation path: + +```bash +cmake -S . -B build -DCMAKE_TOOLCHAIN_FILE=/scripts/buildsystems/vcpkg.cmake +``` +
+ +
+Windows + +On Windows, use vcpkg to install the MongoDB C driver: + +```bash +vcpkg install mongo-c-driver +``` + +Navigate into the project directory, then configure and build: + +```bash +cd docs-get-started/c/hello-world +cmake -S . -B build -DCMAKE_TOOLCHAIN_FILE=/scripts/buildsystems/vcpkg.cmake +cmake --build build --config Release +``` + +Replace `` with your vcpkg installation path. +
+ +For other installation methods, see the +[C driver installation guide](https://www.mongodb.com/docs/languages/c/c-driver/current/get-started/). + +## Connect to MongoDB + +Set your connection string as an environment variable, replacing +`` with your connection string: + +```bash +export MONGODB_URI="" +``` + +## Run the Application + +On macOS and Linux, run the following command: + +```bash +./build/hello-world +``` + +On Windows, use the following command instead: + +```bash +./build/Release/hello-world.exe +``` + +When you run the app, it inserts a few product documents into the +`get_started.products` collection, then queries and prints one of them: + +``` +{ "_id" : ObjectId("..."), "name" : "Wireless Mouse", "category" : "Electronics", "price" : NumberDecimal("24.99"), "tags" : ["wireless", "usb", "ergonomic"] } +``` + +You can run the app more than once. It clears the collection before +each run, so the results stay consistent. + +If you encounter an error or see no output, verify that you set the +`MONGODB_URI` environment variable correctly. diff --git a/c/hello-world/hello-world.c b/c/hello-world/hello-world.c new file mode 100644 index 0000000..e9f8bf4 --- /dev/null +++ b/c/hello-world/hello-world.c @@ -0,0 +1,164 @@ +#include +#include +#include + +typedef struct { + const char *name; + const char *category; + const char *price; + const char *tags[8]; + size_t tag_count; +} sample_product_t; + +/* A few sample product documents seeded by this app so you can run it + * without loading an external dataset. */ +static const sample_product_t sample_products[] = { + {"Wireless Mouse", "Electronics", "24.99", {"wireless", "usb", "ergonomic"}, 3}, + {"Standing Desk", "Furniture", "349.99", {"adjustable", "office"}, 2}, + {"Noise-Cancelling Headphones", "Electronics", "199.99", {"bluetooth", "wireless", "over-ear"}, 3}, +}; + +#define SAMPLE_PRODUCT_COUNT (sizeof (sample_products) / sizeof (sample_products[0])) + +static bson_t * +product_to_bson (const sample_product_t *product) +{ + bson_t *doc = bson_new (); + bson_decimal128_t price; + bson_array_builder_t *tags; + + bson_decimal128_from_string (product->price, &price); + BSON_APPEND_UTF8 (doc, "name", product->name); + BSON_APPEND_UTF8 (doc, "category", product->category); + BSON_APPEND_DECIMAL128 (doc, "price", &price); + + bson_append_array_builder_begin (doc, "tags", -1, &tags); + for (size_t i = 0; i < product->tag_count; i++) { + bson_array_builder_append_utf8 (tags, product->tags[i], -1); + } + bson_append_array_builder_end (doc, tags); + + return doc; +} + +/* Prints a product document using MongoDB Shell-style formatting, + * preserving types such as ObjectId and NumberDecimal. */ +static void +print_shell_product (const bson_t *product) +{ + bson_iter_t iter; + bson_oid_t oid; + char oid_str[25]; + + printf ("{ "); + + if (bson_iter_init_find (&iter, product, "_id")) { + bson_oid_copy (bson_iter_oid (&iter), &oid); + bson_oid_to_string (&oid, oid_str); + printf ("\"_id\" : ObjectId(\"%s\"), ", oid_str); + } + + if (bson_iter_init_find (&iter, product, "name")) { + printf ("\"name\" : \"%s\", ", bson_iter_utf8 (&iter, NULL)); + } + + if (bson_iter_init_find (&iter, product, "category")) { + printf ("\"category\" : \"%s\", ", bson_iter_utf8 (&iter, NULL)); + } + + if (bson_iter_init_find (&iter, product, "price")) { + bson_decimal128_t price; + char price_str[BSON_DECIMAL128_STRING]; + bson_iter_decimal128 (&iter, &price); + bson_decimal128_to_string (&price, price_str); + printf ("\"price\" : NumberDecimal(\"%s\"), ", price_str); + } + + if (bson_iter_init_find (&iter, product, "tags")) { + bson_iter_t tags_iter; + bool first = true; + + printf ("\"tags\" : ["); + BSON_ASSERT (bson_iter_recurse (&iter, &tags_iter)); + while (bson_iter_next (&tags_iter)) { + printf ("%s\"%s\"", first ? "" : ", ", bson_iter_utf8 (&tags_iter, NULL)); + first = false; + } + printf ("]"); + } + + printf (" }\n"); +} + +int +main (void) +{ + mongoc_client_t *client; + mongoc_collection_t *products; + const char *uri_string; + bson_t empty_filter = BSON_INITIALIZER; + bson_t name_filter = BSON_INITIALIZER; + bson_t *inserts[SAMPLE_PRODUCT_COUNT]; + bson_error_t error; + const bson_t *product; + mongoc_cursor_t *cursor; + int exit_code = EXIT_SUCCESS; + + uri_string = getenv ("MONGODB_URI"); + if (!uri_string) { + fprintf (stderr, "Set the MONGODB_URI environment variable before running this app.\n"); + return EXIT_FAILURE; + } + + mongoc_init (); + + client = mongoc_client_new (uri_string); + if (!client) { + fprintf (stderr, "Failed to parse MONGODB_URI.\n"); + mongoc_cleanup (); + return EXIT_FAILURE; + } + + products = mongoc_client_get_collection (client, "get_started", "products"); + + /* Seed the collection so the app has data to query. Clearing the + * collection first keeps results consistent across repeated runs. */ + if (!mongoc_collection_delete_many (products, &empty_filter, NULL, NULL, &error)) { + fprintf (stderr, "Delete failed: %s\n", error.message); + exit_code = EXIT_FAILURE; + goto cleanup; + } + + for (size_t i = 0; i < SAMPLE_PRODUCT_COUNT; i++) { + inserts[i] = product_to_bson (&sample_products[i]); + } + if (!mongoc_collection_insert_many ( + products, (const bson_t **) inserts, SAMPLE_PRODUCT_COUNT, NULL, NULL, &error)) { + fprintf (stderr, "Insert failed: %s\n", error.message); + exit_code = EXIT_FAILURE; + } + for (size_t i = 0; i < SAMPLE_PRODUCT_COUNT; i++) { + bson_destroy (inserts[i]); + } + if (exit_code == EXIT_FAILURE) { + goto cleanup; + } + + BSON_APPEND_UTF8 (&name_filter, "name", "Wireless Mouse"); + cursor = mongoc_collection_find_with_opts (products, &name_filter, NULL, NULL); + if (mongoc_cursor_next (cursor, &product)) { + print_shell_product (product); + } else if (mongoc_cursor_error (cursor, &error)) { + fprintf (stderr, "Query failed: %s\n", error.message); + exit_code = EXIT_FAILURE; + } + mongoc_cursor_destroy (cursor); + +cleanup: + bson_destroy (&name_filter); + mongoc_collection_destroy (products); + mongoc_client_destroy (client); + mongoc_cleanup (); + + return exit_code; +} diff --git a/cpp/hello-world/.gitignore b/cpp/hello-world/.gitignore new file mode 100644 index 0000000..567609b --- /dev/null +++ b/cpp/hello-world/.gitignore @@ -0,0 +1 @@ +build/ diff --git a/cpp/hello-world/CMakeLists.txt b/cpp/hello-world/CMakeLists.txt new file mode 100644 index 0000000..158d167 --- /dev/null +++ b/cpp/hello-world/CMakeLists.txt @@ -0,0 +1,12 @@ +cmake_minimum_required(VERSION 3.15) + +project(hello-world CXX) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(mongocxx 4.0 REQUIRED) + +add_executable(hello-world main.cpp) + +target_link_libraries(hello-world PRIVATE mongo::mongocxx_shared) diff --git a/cpp/hello-world/README.md b/cpp/hello-world/README.md new file mode 100644 index 0000000..c3c363e --- /dev/null +++ b/cpp/hello-world/README.md @@ -0,0 +1,124 @@ +# Get Started with the MongoDB C++ Driver + +This sample application connects to a MongoDB deployment, seeds a small +set of sample product documents, and retrieves one of them. Because the +app inserts its own data, you don't need to load an external dataset. + +## Prerequisites + +Before you begin, complete the [Atlas Get Started guide](https://www.mongodb.com/docs/get-started/) +to create a free Atlas deployment and save your database user +credentials. + +You also need the following components installed in your development environment: + +- CMake 3.15 or later +- A C++17-compatible compiler +- [vcpkg](https://github.com/microsoft/vcpkg) (Windows and Linux) + +The commands in this guide assume a Bash compatible shell. + +## Installation + +Clone this repository: + +```bash +git clone https://github.com/mongodb/docs-get-started +``` + +### Install the MongoDB C++ Driver + +This project requires MongoDB C++ driver (mongocxx) 4.0 or later. Install +it with your platform's package manager. + +
+macOS / Linux + +On macOS, install the MongoDB C++ driver with [Homebrew](https://brew.sh/): + +```bash +brew install mongo-cxx-driver +``` + +On Linux, most distribution packages are too old to satisfy this +requirement. Use vcpkg instead: + +```bash +vcpkg install mongo-cxx-driver +``` + +Navigate into the project directory, then configure and build: + +```bash +cd docs-get-started/cpp/hello-world +cmake -S . -B build +cmake --build build +``` + +If you installed the driver with vcpkg, add the vcpkg toolchain file to +the configure step so CMake can locate it, replacing `` with +your vcpkg installation path: + +```bash +cmake -S . -B build -DCMAKE_TOOLCHAIN_FILE=/scripts/buildsystems/vcpkg.cmake +``` +
+ +
+Windows + +On Windows, use vcpkg to install the MongoDB C++ driver: + +```bash +vcpkg install mongo-cxx-driver +``` + +Navigate into the project directory, then configure and build: + +```bash +cd docs-get-started/cpp/hello-world +cmake -S . -B build -DCMAKE_TOOLCHAIN_FILE=/scripts/buildsystems/vcpkg.cmake +cmake --build build --config Release +``` + +Replace `` with your vcpkg installation path. +
+ +For other installation methods, see the +[C++ driver installation guide](https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/installation/). + +## Connect to MongoDB + +Set your connection string as an environment variable, replacing +`` with your connection string: + +```bash +export MONGODB_URI="" +``` + +## Run the Application + +On macOS and Linux, run the following command: + +```bash +./build/hello-world +``` + +On Windows, use the following command instead: + +```bash +./build/Release/hello-world.exe +``` + +When you run the app, it inserts a few product documents into the +`get_started.products` collection, then queries and prints one of them: + +``` +{ "_id" : { "$oid" : "..." }, "name" : "Wireless Mouse", "category" : "Electronics", "price" : 24.99, "tags" : [ "wireless", "usb", "ergonomic" ] } +``` + +You can run the app more than once. It clears the collection before +each run, so the results stay consistent. + +If you encounter an error or see no output, verify that you set the +`MONGODB_URI` environment variable correctly. diff --git a/cpp/hello-world/main.cpp b/cpp/hello-world/main.cpp new file mode 100644 index 0000000..30ff610 --- /dev/null +++ b/cpp/hello-world/main.cpp @@ -0,0 +1,88 @@ +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +using bsoncxx::builder::basic::kvp; +using bsoncxx::builder::basic::make_array; +using bsoncxx::builder::basic::make_document; + +// A few sample product documents seeded by this app so you can run it +// without loading an external dataset. +std::vector sample_products() { + std::vector products; + + products.push_back(make_document( + kvp("name", "Wireless Mouse"), + kvp("category", "Electronics"), + kvp("price", 24.99), + kvp("tags", make_array("wireless", "usb", "ergonomic")))); + + products.push_back(make_document( + kvp("name", "Standing Desk"), + kvp("category", "Furniture"), + kvp("price", 349.99), + kvp("tags", make_array("adjustable", "office")))); + + products.push_back(make_document( + kvp("name", "Noise-Cancelling Headphones"), + kvp("category", "Electronics"), + kvp("price", 199.99), + kvp("tags", make_array("bluetooth", "wireless", "over-ear")))); + + return products; +} + +int main() { + const char* uri_env = std::getenv("MONGODB_URI"); + if (uri_env == nullptr) { + std::cerr << "Set the MONGODB_URI environment variable to your " + "connection string.\n"; + return EXIT_FAILURE; + } + + mongocxx::instance instance{}; + mongocxx::client client{mongocxx::uri{uri_env}}; + + auto database = client["get_started"]; + auto products = database["products"]; + + // Seed the collection so the app has data to query. Clearing the + // collection first keeps results consistent across repeated runs. + products.delete_many({}); + products.insert_many(sample_products()); + + auto filter = make_document(kvp("name", "Wireless Mouse")); + auto product = products.find_one(filter.view()); + if (product) { + auto view = product->view(); + + std::array buf; + auto [ptr, ec] = std::to_chars( + buf.data(), buf.data() + buf.size(), view["price"].get_double().value); + std::string price(buf.data(), ptr); + + std::cout << "{ \"_id\" : { \"$oid\" : \"" + << view["_id"].get_oid().value.to_string() << "\" }" + << ", \"name\" : \"" << view["name"].get_string().value << "\"" + << ", \"category\" : \"" << view["category"].get_string().value + << "\"" + << ", \"price\" : " << price << ", \"tags\" : ["; + bool first = true; + for (auto tag : view["tags"].get_array().value) { + std::cout << (first ? " " : ", ") << "\"" << tag.get_string().value + << "\""; + first = false; + } + std::cout << " ] }\n"; + } + + return EXIT_SUCCESS; +} diff --git a/java-rs/hello-world/.gitignore b/java-rs/hello-world/.gitignore new file mode 100644 index 0000000..2f7896d --- /dev/null +++ b/java-rs/hello-world/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/java-rs/hello-world/README.md b/java-rs/hello-world/README.md new file mode 100644 index 0000000..d3900c2 --- /dev/null +++ b/java-rs/hello-world/README.md @@ -0,0 +1,67 @@ +# Get Started with the MongoDB Java Reactive Streams Driver + +This sample application connects to a MongoDB deployment, seeds a small +set of sample product documents, and retrieves one of them. Because the +app inserts its own data, you don't need to load an external dataset. + +The app uses the MongoDB Reactive Streams Java driver together with +[Project Reactor](https://projectreactor.io/) to consume the `Publisher` +results that the driver returns. + +## Prerequisites + +Before you begin, complete the [Atlas Get Started guide](https://www.mongodb.com/docs/get-started/) +to create a free Atlas deployment and save your database user +credentials. + +You also need the following components installed in your development environment: + +- JDK version 21 or later +- Maven + +The commands in this guide assume a Bash compatible shell. + +## Installation + +Clone this repository: + +```bash +git clone https://github.com/mongodb/docs-get-started +``` + +Navigate into the `java-rs/hello-world` project directory and compile the +application. Maven downloads the MongoDB driver and Project Reactor +declared in `pom.xml`: + +```bash +cd docs-get-started/java-rs/hello-world +mvn compile +``` + +## Connect to MongoDB + +Set your connection string as an environment variable, replacing +`` with your connection string: + +```bash +export MONGODB_URI="" +``` + +## Run the Application + +```bash +mvn compile exec:java +``` + +When you run the app, it inserts a few product documents into the +`get_started.products` collection, then queries and prints one of them: + +``` +{"_id": {"$oid": "..."}, "name": "Wireless Mouse", "category": "Electronics", "price": 24.99, "tags": ["wireless", "usb", "ergonomic"]} +``` + +You can run the app more than once. It clears the collection before +each run, so the results stay consistent. + +If you encounter an error or see no output, verify that you set the +`MONGODB_URI` environment variable correctly. diff --git a/java-rs/hello-world/pom.xml b/java-rs/hello-world/pom.xml new file mode 100644 index 0000000..b315939 --- /dev/null +++ b/java-rs/hello-world/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + + com.mongodb + hello-world-reactive-streams + 1.0.0 + jar + + + 21 + UTF-8 + HelloWorld + + + + + + org.mongodb + mongodb-driver-bom + 5.9.1 + pom + import + + + io.projectreactor + reactor-bom + 2025.0.0 + pom + import + + + + + + + org.mongodb + mongodb-driver-reactivestreams + + + io.projectreactor + reactor-core + + + + + + + org.codehaus.mojo + exec-maven-plugin + 3.5.0 + + + + diff --git a/java-rs/hello-world/src/main/java/HelloWorld.java b/java-rs/hello-world/src/main/java/HelloWorld.java new file mode 100644 index 0000000..9f20bdd --- /dev/null +++ b/java-rs/hello-world/src/main/java/HelloWorld.java @@ -0,0 +1,50 @@ +import static com.mongodb.client.model.Filters.eq; + +import com.mongodb.reactivestreams.client.MongoClient; +import com.mongodb.reactivestreams.client.MongoClients; +import com.mongodb.reactivestreams.client.MongoCollection; +import com.mongodb.reactivestreams.client.MongoDatabase; +import java.util.List; +import org.bson.Document; +import reactor.core.publisher.Mono; + +public class HelloWorld { + + // A few sample product documents seeded by this app so you can run + // it without loading an external dataset. + private static final List SAMPLE_PRODUCTS = List.of( + new Document("name", "Wireless Mouse") + .append("category", "Electronics") + .append("price", 24.99) + .append("tags", List.of("wireless", "usb", "ergonomic")), + new Document("name", "Standing Desk") + .append("category", "Furniture") + .append("price", 349.99) + .append("tags", List.of("adjustable", "office")), + new Document("name", "Noise-Cancelling Headphones") + .append("category", "Electronics") + .append("price", 199.99) + .append("tags", List.of("bluetooth", "wireless", "over-ear")) + ); + + public static void main(String[] args) { + String uri = System.getenv("MONGODB_URI"); + + try (MongoClient client = MongoClients.create(uri)) { + MongoDatabase database = client.getDatabase("get_started"); + MongoCollection products = database.getCollection("products"); + + // Each reactive driver call returns a Publisher. Wrapping it in a + // Reactor Mono and calling block() runs the operation and waits for + // it to complete before moving on. + + // Seed the collection so the app has data to query. Clearing the + // collection first keeps results consistent across repeated runs. + Mono.from(products.deleteMany(new Document())).block(); + Mono.from(products.insertMany(SAMPLE_PRODUCTS)).block(); + + Document product = Mono.from(products.find(eq("name", "Wireless Mouse")).first()).block(); + System.out.println(product.toJson()); + } + } +} diff --git a/kotlin-coroutine/hello-world/.gitignore b/kotlin-coroutine/hello-world/.gitignore new file mode 100644 index 0000000..2f7896d --- /dev/null +++ b/kotlin-coroutine/hello-world/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/kotlin-coroutine/hello-world/README.md b/kotlin-coroutine/hello-world/README.md new file mode 100644 index 0000000..1db2de9 --- /dev/null +++ b/kotlin-coroutine/hello-world/README.md @@ -0,0 +1,63 @@ +# Get Started with the MongoDB Kotlin Coroutine Driver + +This sample application connects to a MongoDB deployment, seeds a small +set of sample product documents, and retrieves one of them. Because the +app inserts its own data, you don't need to load an external dataset. + +## Prerequisites + +Before you begin, complete the [Atlas Get Started guide](https://www.mongodb.com/docs/get-started/) +to create a free Atlas deployment and save your database user +credentials. + +You also need the following components installed in your development environment: + +- JDK version 21 or later +- Maven + +The commands in this guide assume a Bash compatible shell. + +## Installation + +Clone this repository: + +```bash +git clone https://github.com/mongodb/docs-get-started +``` + +Navigate into the `kotlin-coroutine/hello-world` project directory and +compile the application. Maven downloads the MongoDB driver and Kotlin +dependencies declared in `pom.xml`: + +```bash +cd docs-get-started/kotlin-coroutine/hello-world +mvn compile +``` + +## Connect to MongoDB + +Set your connection string as an environment variable, replacing +`` with your connection string: + +```bash +export MONGODB_URI="" +``` + +## Run the Application + +```bash +mvn compile exec:java +``` + +When you run the app, it inserts a few product documents into the +`get_started.products` collection, then queries and prints one of them: + +``` +{"_id": {"$oid": "..."}, "name": "Wireless Mouse", "category": "Electronics", "price": 24.99, "tags": ["wireless", "usb", "ergonomic"]} +``` + +You can run the app more than once. It clears the collection before +each run, so the results stay consistent. + +If you encounter an error or see no output, verify that you set the +`MONGODB_URI` environment variable correctly. diff --git a/kotlin-coroutine/hello-world/pom.xml b/kotlin-coroutine/hello-world/pom.xml new file mode 100644 index 0000000..4bc6dff --- /dev/null +++ b/kotlin-coroutine/hello-world/pom.xml @@ -0,0 +1,75 @@ + + + 4.0.0 + + com.mongodb + hello-world-kotlin-coroutine + 1.0.0 + jar + + + 2.1.0 + 21 + UTF-8 + HelloWorldKt + + + + + + org.mongodb + mongodb-driver-bom + 5.9.1 + pom + import + + + + + + + org.mongodb + mongodb-driver-kotlin-coroutine + + + org.jetbrains.kotlin + kotlin-stdlib + ${kotlin.version} + + + org.jetbrains.kotlinx + kotlinx-coroutines-core + 1.9.0 + + + + + src/main/kotlin + + + org.jetbrains.kotlin + kotlin-maven-plugin + ${kotlin.version} + + 21 + + + + compile + compile + + compile + + + + + + org.codehaus.mojo + exec-maven-plugin + 3.5.0 + + + + diff --git a/kotlin-coroutine/hello-world/src/main/kotlin/HelloWorld.kt b/kotlin-coroutine/hello-world/src/main/kotlin/HelloWorld.kt new file mode 100644 index 0000000..ce2e0f6 --- /dev/null +++ b/kotlin-coroutine/hello-world/src/main/kotlin/HelloWorld.kt @@ -0,0 +1,43 @@ +import com.mongodb.client.model.Filters.eq +import com.mongodb.kotlin.client.coroutine.MongoClient +import kotlinx.coroutines.flow.firstOrNull +import kotlinx.coroutines.runBlocking +import org.bson.Document + +// A few sample product documents seeded by this app so you can run +// it without loading an external dataset. +private val SAMPLE_PRODUCTS = listOf( + Document("name", "Wireless Mouse") + .append("category", "Electronics") + .append("price", 24.99) + .append("tags", listOf("wireless", "usb", "ergonomic")), + Document("name", "Standing Desk") + .append("category", "Furniture") + .append("price", 349.99) + .append("tags", listOf("adjustable", "office")), + Document("name", "Noise-Cancelling Headphones") + .append("category", "Electronics") + .append("price", 199.99) + .append("tags", listOf("bluetooth", "wireless", "over-ear")) +) + +fun main() = runBlocking { + val uri = System.getenv("MONGODB_URI") + + MongoClient.create(uri).use { client -> + val database = client.getDatabase("get_started") + val products = database.getCollection("products") + + // The coroutine driver exposes suspending functions, so these + // calls run inside the runBlocking coroutine. + + // Seed the collection so the app has data to query. Clearing + // the collection first keeps results consistent across + // repeated runs. + products.deleteMany(Document()) + products.insertMany(SAMPLE_PRODUCTS) + + val product = products.find(eq("name", "Wireless Mouse")).firstOrNull() + println(product?.toJson()) + } +} diff --git a/kotlin-sync/hello-world/.gitignore b/kotlin-sync/hello-world/.gitignore new file mode 100644 index 0000000..2f7896d --- /dev/null +++ b/kotlin-sync/hello-world/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/kotlin-sync/hello-world/README.md b/kotlin-sync/hello-world/README.md new file mode 100644 index 0000000..a0fa32c --- /dev/null +++ b/kotlin-sync/hello-world/README.md @@ -0,0 +1,63 @@ +# Get Started with the MongoDB Kotlin Sync Driver + +This sample application connects to a MongoDB deployment, seeds a small +set of sample product documents, and retrieves one of them. Because the +app inserts its own data, you don't need to load an external dataset. + +## Prerequisites + +Before you begin, complete the [Atlas Get Started guide](https://www.mongodb.com/docs/get-started/) +to create a free Atlas deployment and save your database user +credentials. + +You also need the following components installed in your development environment: + +- JDK version 21 or later +- Maven + +The commands in this guide assume a Bash compatible shell. + +## Installation + +Clone this repository: + +```bash +git clone https://github.com/mongodb/docs-get-started +``` + +Navigate into the `kotlin-sync/hello-world` project directory and +compile the application. Maven downloads the MongoDB driver and Kotlin +dependencies declared in `pom.xml`: + +```bash +cd docs-get-started/kotlin-sync/hello-world +mvn compile +``` + +## Connect to MongoDB + +Set your connection string as an environment variable, replacing +`` with your connection string: + +```bash +export MONGODB_URI="" +``` + +## Run the Application + +```bash +mvn compile exec:java +``` + +When you run the app, it inserts a few product documents into the +`get_started.products` collection, then queries and prints one of them: + +``` +{"_id": {"$oid": "..."}, "name": "Wireless Mouse", "category": "Electronics", "price": 24.99, "tags": ["wireless", "usb", "ergonomic"]} +``` + +You can run the app more than once. It clears the collection before +each run, so the results stay consistent. + +If you encounter an error or see no output, verify that you set the +`MONGODB_URI` environment variable correctly. diff --git a/kotlin-sync/hello-world/pom.xml b/kotlin-sync/hello-world/pom.xml new file mode 100644 index 0000000..3d99bcb --- /dev/null +++ b/kotlin-sync/hello-world/pom.xml @@ -0,0 +1,70 @@ + + + 4.0.0 + + com.mongodb + hello-world-kotlin-sync + 1.0.0 + jar + + + 2.1.0 + 21 + UTF-8 + HelloWorldKt + + + + + + org.mongodb + mongodb-driver-bom + 5.9.1 + pom + import + + + + + + + org.mongodb + mongodb-driver-kotlin-sync + + + org.jetbrains.kotlin + kotlin-stdlib + ${kotlin.version} + + + + + src/main/kotlin + + + org.jetbrains.kotlin + kotlin-maven-plugin + ${kotlin.version} + + 21 + + + + compile + compile + + compile + + + + + + org.codehaus.mojo + exec-maven-plugin + 3.5.0 + + + + diff --git a/kotlin-sync/hello-world/src/main/kotlin/HelloWorld.kt b/kotlin-sync/hello-world/src/main/kotlin/HelloWorld.kt new file mode 100644 index 0000000..2a55243 --- /dev/null +++ b/kotlin-sync/hello-world/src/main/kotlin/HelloWorld.kt @@ -0,0 +1,38 @@ +import com.mongodb.client.model.Filters.eq +import com.mongodb.kotlin.client.MongoClient +import org.bson.Document + +// A few sample product documents seeded by this app so you can run +// it without loading an external dataset. +private val SAMPLE_PRODUCTS = listOf( + Document("name", "Wireless Mouse") + .append("category", "Electronics") + .append("price", 24.99) + .append("tags", listOf("wireless", "usb", "ergonomic")), + Document("name", "Standing Desk") + .append("category", "Furniture") + .append("price", 349.99) + .append("tags", listOf("adjustable", "office")), + Document("name", "Noise-Cancelling Headphones") + .append("category", "Electronics") + .append("price", 199.99) + .append("tags", listOf("bluetooth", "wireless", "over-ear")) +) + +fun main() { + val uri = System.getenv("MONGODB_URI") + + MongoClient.create(uri).use { client -> + val database = client.getDatabase("get_started") + val products = database.getCollection("products") + + // Seed the collection so the app has data to query. Clearing + // the collection first keeps results consistent across + // repeated runs. + products.deleteMany(Document()) + products.insertMany(SAMPLE_PRODUCTS) + + val product = products.find(eq("name", "Wireless Mouse")).firstOrNull() + println(product?.toJson()) + } +} diff --git a/php/hello-world/.gitignore b/php/hello-world/.gitignore new file mode 100644 index 0000000..e463882 --- /dev/null +++ b/php/hello-world/.gitignore @@ -0,0 +1,3 @@ +vendor/ +composer.lock +pie.phar diff --git a/php/hello-world/README.md b/php/hello-world/README.md new file mode 100644 index 0000000..5db21a1 --- /dev/null +++ b/php/hello-world/README.md @@ -0,0 +1,164 @@ +# Get Started with the MongoDB PHP Library + +This sample application connects to a MongoDB deployment, seeds a small +set of sample product documents, and retrieves one of them. Because the +app inserts its own data, you don't need to load an external dataset. + +## Prerequisites + +Before you begin, complete the [Atlas Get Started guide](https://www.mongodb.com/docs/get-started/) +to create a free Atlas deployment and save your database user +credentials. + +You also need the following components installed in your development environment: + +- PHP version 8.2 or later +- Composer version 2.0 or later +- PIE version 1.4 or later + +The commands in this guide assume a Bash compatible shell. + +## Installation + +Clone this repository: + +```bash +git clone https://github.com/mongodb/docs-get-started +``` + +### Install the MongoDB PHP Extension + +The `mongodb` extension is a native PHP extension, so Composer can't +install it for you. Install it with PIE: + +```bash +pie install mongodb/mongodb-extension +``` + +On Windows, PIE is distributed as a PHAR rather than an executable, so +run it through `php` from the directory containing `pie.phar`: + +```bash +php pie.phar install mongodb/mongodb-extension +``` + +PIE requires elevated privileges to write the extension into your PHP +installation, so it might prompt you for your password. + +On success, PIE prints a line confirming the extension is loaded, +followed by the path to your PHP binary: + +``` +✅ Extension is enabled and loaded in +``` + +Verify that the extension is enabled: + +```bash +php -m | grep mongodb +``` + +For more details, see the +[PHP library installation guide](https://www.mongodb.com/docs/php-library/current/get-started/). + +### Install the Project Dependencies + +Navigate into the `php/hello-world` project directory and install the +MongoDB PHP library with Composer: + +```bash +cd docs-get-started/php/hello-world +composer install +``` + +## Connect to MongoDB + +Set your connection string as an environment variable, replacing +`` with your connection string: + +```bash +export MONGODB_URI="" +``` + +## Run the Application + +```bash +php src/HelloWorld.php +``` + +When you run the app, it inserts a few product documents into the +`get_started.products` collection, then queries and prints one of them: + +``` +{"_id":{"$oid":"..."},"name":"Wireless Mouse","category":"Electronics","price":24.99,"tags":["wireless","usb","ergonomic"]} +``` + +You can run the app more than once. It clears the collection before +each run, so the results stay consistent. + +If you encounter an error or see no output, verify that you set the +`MONGODB_URI` environment variable correctly. + +## Troubleshooting + +### PIE fails to download the extension + +PIE downloads the extension over HTTPS, which requires the `openssl` +extension. If `pie install` fails with a download or TLS error, confirm +that `openssl` is enabled: + +```bash +php -m +``` + +If openssl is not enabled, find your configuration file: + +```bash +php --ini +``` + +Open the file listed as `Loaded Configuration File` in a text editor. On +Windows, you can use Notepad. Find the following line: + +```ini +;extension=openssl +``` + +Remove the leading semicolon so that it reads: + +```ini +extension=openssl +``` + +Save the file, then run the install command again. + +### Connection fails with "SSL not enabled in this build" + +Atlas requires TLS. If connecting fails with +`Can't create SSL client, SSL not enabled in this build`, the extension +was built without TLS support. This can happen on Linux when the OpenSSL +development headers are missing at build time: the extension still +compiles, installs, and loads, so `php -m` lists it, but it cannot +connect. + +Check how the extension was built: + +```bash +php --ri mongodb | grep SSL +``` + +If it reports `libmongoc SSL => disabled`, install the OpenSSL +development headers: + +```bash +sudo apt-get install libssl-dev +``` + +Then rebuild the extension: + +```bash +pie install --force mongodb/mongodb-extension +``` + +`php --ri mongodb | grep SSL` should now report +`libmongoc SSL => enabled`. diff --git a/php/hello-world/composer.json b/php/hello-world/composer.json new file mode 100644 index 0000000..9ed8095 --- /dev/null +++ b/php/hello-world/composer.json @@ -0,0 +1,10 @@ +{ + "name": "mongodb/hello-world-php", + "description": "Get Started sample application for the MongoDB PHP library", + "type": "project", + "require": { + "php": ">=8.2", + "ext-mongodb": "^2.0", + "mongodb/mongodb": "^2.0" + } +} diff --git a/php/hello-world/src/HelloWorld.php b/php/hello-world/src/HelloWorld.php new file mode 100644 index 0000000..5b18e43 --- /dev/null +++ b/php/hello-world/src/HelloWorld.php @@ -0,0 +1,46 @@ + 'Wireless Mouse', + 'category' => 'Electronics', + 'price' => 24.99, + 'tags' => ['wireless', 'usb', 'ergonomic'], + ], + [ + 'name' => 'Standing Desk', + 'category' => 'Furniture', + 'price' => 349.99, + 'tags' => ['adjustable', 'office'], + ], + [ + 'name' => 'Noise-Cancelling Headphones', + 'category' => 'Electronics', + 'price' => 199.99, + 'tags' => ['bluetooth', 'wireless', 'over-ear'], + ], +]; + +$client = new Client($uri); +$products = $client->get_started->products; + +// Seed the collection so the app has data to query. Clearing the +// collection first keeps results consistent across repeated runs. +$products->deleteMany([]); +$products->insertMany($sampleProducts); + +$product = $products->findOne(['name' => 'Wireless Mouse']); + +echo json_encode($product), "\n";