Tutorial:
https://mongodb.github.io/mongo-cxx-driver/mongocxx-v3/tutorial/

Example code:

/**
 * Test inserting into db
 */
void db::test() {

  //create connection
  uri    Uri("mongodb://localhost:27017");
  client Client(Uri);

  //use a database
  database Db = Client["valgo"];

  //use a collection in db
  collection Collection = Db["tests"];

  //create a test document
  auto  Builder  = document{};
  value Document = Builder
      <<"name"  <<"MongoDB"
      <<"type"  <<"database"
      <<"count" <<1
      <<"versions" 
      <<open_array
          <<"v3.2" <<"v3.0" <<"v2.6"
      <<close_array
      <<"info" 
      <<open_document
          <<"x" <<203
          <<"y" <<102
      <<close_document
  <<finalize;

  //test printing 
  view    View    = Document.view();
  element Element = View["name"];
  cout <<"\ndb::test()\n";
  cout <<"Name: " <<Element.get_utf8().value.to_string() <<"\n";

  //test insert
  auto Result = Collection.insert_one(Document.view());

  //print result
  cout <<"Id: " <<Result->inserted_id().get_oid().value.to_string() <<"\n";
  cout.flush();
}

Notes:

  • “inserted_id” method to be called using pointer instead of variable dot.
  • “insert_one” method take “Document.view()” as argument and not “Document”
Advertisements