Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ includes its own setup instructions.
## Available Client Libraries

- C
- C++
- [C++](cpp/hello-world/README.md)
- EF
- [Go](go/hello-world/README.md)
- Hibernate
Expand Down
1 change: 1 addition & 0 deletions cpp/hello-world/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
build/
12 changes: 12 additions & 0 deletions cpp/hello-world/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -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)
66 changes: 66 additions & 0 deletions cpp/hello-world/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# 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:

- A C++17-compatible compiler
- CMake 3.15 or later
- The MongoDB C++ driver (mongocxx) 4.0 or later

## Installation

Clone this repository:

```bash
git clone https://github.com/mongodb/mongodb-code-examples
```

Install the MongoDB C++ driver (mongocxx). Follow the
[C++ driver installation guide](https://www.mongodb.com/docs/languages/cpp/cpp-driver/current/installation/)
for your platform.

Navigate into the `cpp/hello-world` project directory and build the
application with CMake:

```bash
cd mongodb-code-examples/cpp/hello-world
cmake -S . -B build
cmake --build build
```

## Connect to MongoDB

Set your connection string as an environment variable, replacing
`<connection string uri>` with your connection string:

```bash
export MONGODB_URI="<connection string uri>"
```

## Run the Application

```bash
./build/hello-world
```

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.
88 changes: 88 additions & 0 deletions cpp/hello-world/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
#include <array>
#include <charconv>
#include <cstdlib>
#include <iostream>
#include <string>

#include <bsoncxx/builder/basic/array.hpp>
#include <bsoncxx/builder/basic/document.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>

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<bsoncxx::document::value> sample_products() {
std::vector<bsoncxx::document::value> 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<char, 32> 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;
}