Connecting to MongoDB On Visual C++ / Visual Studio 2010

Environment / Dependencies:

  • Windows 7 64bit
  • Visual Studio 2010 (Win32-Release target project)
  • MongoDB 2.2.3
  • Git

Visual Studio 2010 sample client project doesn’t appear to compile on the latest version of mongodb source code (2.4.3 at the time of this writing). It seems the last working sample is version 2.2.3. Follow these steps to compile and use it as your starting point

  1. Clone the source code from git:
    git clone git://github.com/mongodb/mongo.git C:mongodbsrc
  2. Open command prompt to C:mongodbsrc, switch to version 2.2.3 by running:
    git checkout r2.2.3
  3. Double click C:mongodbsrcsrcmongoclientexamplessimple_client_demo.vcxproj. If Visual Studio prompt to upgrade, don’t do it
  4. Compile the project on visual studio and test it. Use this as your starting point
  5. If you’re trying to copy the settings into your own project, pay particular attention to following items:
    • Boost cpp files and mongo_client_lib.cpp inclusion
    • VC++ Directories
    • C/C++ –> General –> Additional Include Directories
    • C/C++ –> Preprocessor –> Preprocessor Definitions
    • Linker –> Input –> Additional Dependencies
    • Additional preprocessor definitions only for these boost files: thread.cpp, tss_dll.cpp, tss_pe.cpp
    • Different Output Files for utf8_codecvt_facet.cpp file

Quick Cheat Sheet

// Connecting to mongodb on c++
mongo::DBClientConnection conn;
conn.connect("localhost");

// mongo shell
db.mycoll.insert({name: "Gerry", age: "25"})

// c++
conn.insert("mydb.mycoll", BSON("name" << "Gerry" << "age" << 25));

// mongo shell
db.mycoll.update({name: "Gerry"}, {name: "Gerry", age: "30"}, {upsert: "true"})

// c++
conn.update("mydb.mycoll", BSON("name" << "Gerry"), BSON("name" << "Gerry" << "age" << 30), 1);

Documentations:

  • http://docs.mongodb.org/ecosystem/tutorial/download-and-compile-cpp-driver

Leave a Reply