Simple c++ example

I am looking for a simple c++ example of conencting to a database. The examples provided with the cxx driver are all in the same cmake files as the driver cmake, meaning it is very complex to work out how to build them. Is there a standalone example?

Hi @chris_d,

Please take a look at get-started-cxx repository for a standalone example. It contains a simple example of connecting to MongoDB. This repository is part of the Get-Started project, see also get-started-readme for more information.

For example, to compile a C++ file:

c++ --std=c++11 getstarted.cpp -o getstarted $(pkg-config --cflags --libs libmongocxx)

Regards,
Wan.

1 Like

Thanks, that’s a pretty complex example - I’m looking for something much simpler that just connects, executes a query, and that’s all.
Also this example has docker and pkgconfig requirements that means it’s unsuitable

Is there a simple standalone example?

Hi @chris_d,

The Docker is included if you want to have the environment example as well. The environment includes cmake, pkg-config, MongoDB C driver, etc. In order to compile C++ you need to provide path to the installed library, which could be different depending on your environment setup.

The pkg-config is a helper tool, to insert the correct compiler options. In the case above:

c++ --std=c++11 getstarted.cpp -o getstarted $(pkg-config --cflags --libs libmongocxx)

This would be expanded to:

c++ --std=c++11 getstarted.cpp -o getstarted -I/usr/local/include/mongocxx/v_noabi -I/usr/local/include/bsoncxx/v_noabi -L/usr/local/lib -lmongocxx -lbsoncxx

You could just take the code example on the repository (i.e. cxx/getstarted.cpp) and compile by constructing your own c++ build command.

Regards,
Wan.

1 Like