C++驱动库

A C++ driver is available for communicating with the MongoDB. As the database is written in C++, the driver actually uses some core MongoDB code. This is the same driver that the database uses itself for replication.

The driver has been compiled successfully on Linux, OS X, Windows, and Solaris.

See the following:

Additional Notes

  • The Building documentation covers compiling the entire database, but some of the notes there may be helpful for compiling client applications too.
  • There is a pure C driver for MongoDB, but for true C++ apps we recommend using the C++ driver.

C++ BSON Library

The MongoDB C++ driver library includes a bson package that implements the BSON specification (see http://www.bsonspec.org). This library can be used standalone for object serialization and deserialization even when one is not using MongoDB at all.

Include bson/bson.h or db/jsobj.h in your application (not both). bson.h is new and may not work in some situations, was is good for light header-only usage of BSON (see the bsondemo.cpp example).

Key classes:

See BSON examples in the Getting Started guide

Standalone Usage

You can use the C++ BSON library without MongoDB. Most BSON methods under the bson/ directory are header-only. They require boost, but headers only.

See the bsondemo.cpp example at github.com

Short Class Names

Add

using namespace bson;

to your code to use the following shorter more C++ style names for the BSON classes:

// from bsonelement.h
namespace bson {
    typedef mongo::BSONElement be;
    typedef mongo::BSONObj bo;
    typedef mongo::BSONObjBuilder bob;
}

(Or one could use bson::bo fully qualified for example).

Also available is bo::iterator as a synonym for BSONObjIterator.

C++ DBClientConnection

The C++ driver includes several classes for managing collections under the parent class DBClientInterface.

DBClientConnection is our normal connection class for a connection to a single MongoDB database server (or shard manager). Other classes exist for connecting to a replica set.

See http://api.mongodb.org/cplusplus for details on each of the above classes.

C++ getLastError

For an example, see client/simple_client_demo.cpp.

Also see getLastError Command.