from : http://www.mongodb.org/pages/viewpage.action?pageId=133415
C++ Tutorial
This document is an introduction to usage of the MongoDB database from a C++ program. First, install Mongo -- see the Quickstart for details. Next, you may wish to take a look at the Developer's Tour guide for a language independent look at how to use MongoDB. Also, we suggest some basic familiarity with the mongo shell -- the shell is one's primary database administration tool and is useful for manually inspecting the contents of a database after your C++ program runs. Installing the Driver Library and HeadersA good source for general information about setting up a MongoDB development environment on various operating systems is the buildingpage. The normal database distribution used to include the C++ driver, but there were many problems with library version mismatches so now you have to build from source. You can either get the full source code for the database and just build the C++ driver or download the driverseparately and build it. UnixFor Unix, the Mongo driver library is libmongoclient.a. For either build, run scons --help to see all options. Full Database Source Driver BuildTo install the libraries, run:
--full tells the install target to include the library and header files; by default library and header files are installed in /usr/local. You can use --prefix to change the install path: scons --prefix /opt/mongo --full install. In version 2.0, you can also specify --sharedclient to build a shared library instead of a statically linked library. This feature is not yet working properly in 2.2, see SERVER-6514. Driver BuildIf you download the driver source code separately, you can build it by running scons (no options). WindowsFor more information on Boost setup see the Building for Windows page. CompilingThe C++ driver requires the pcre and boost libraries (with headers) to compile. Be sure they are in your include and lib paths. You can usually install them from your OS's package manager if you don't already have them. Writing Client CodeNote: for brevity, the examples below are simply inline code. In a real application one will define classes for each database object typically. ConnectingLet's make a tutorial.cpp file that connects to the database (see client/examples/tutorial.cpp for full text of the examples below):
If you are using gcc on Linux or OS X, you would compile with something like this, depending on location of your include files and libraries:
BSONThe Mongo database stores data in BSON format. BSON is a binary object format that is JSON-like in terms of the data which can be stored (some extensions exist, for example, a Date datatype). To save data in the database we must create objects of class BSONObj. The components of a BSONObj are represented asBSONElement objects. We use BSONObjBuilder to make BSON objects, and BSONObjIterator to enumerate BSON objects. Let's now create a BSON "person" object which contains name and age. We might invoke:
Or more concisely:
We can also create objects with a stream-oriented syntax:
The macro BSON lets us be even more compact:
Use the GENOID helper to add an object id to your object. The server will add an _id automatically if it is not included explicitly.
GENOID should be at the beginning of the generated object. We can do something similar with the non-stream builder syntax:
Other helpers are listed here. InsertingWe now save our person object in a persons collection in the database:
The first parameter to insert is the namespace. tutorial is the database and persons is the collection name. QueryingLet's now fetch all objects from the persons collection, and display them. We'll also show here how to use count().
BSONObj() is an empty BSON object -- it represents {} which indicates an empty query pattern (an empty query is a query for all objects). We use BSONObj::toString() above to print out information about each object retrieved. BSONObj::toString is a diagnostic function which prints an abbreviated JSON string representation of the object. For full JSON output, use BSONObj::jsonString. Let's now write a function which prints out the name (only) of all persons in the collection whose age is a given value:
getStringField() is a helper that assumes the "name" field is of type string. To manipulate an element in a more generic fashion we can retrieve the particular BSONElement from the enclosing object: See the api docs, and jsobj.h, for more information. Our query above, written as JSON, is of the form
Queries are BSON objects of a particular format -- in fact, we could have used the BSON() macro above instead of QUERY(). See classQuery in dbclient.h for more information on Query objects, and the Sorting section below. In the mongo shell (which uses javascript), we could invoke:
IndexingLet's suppose we want to have an index on age so that our queries are fast. We would use:
The ensureIndex method checks if the index exists; if it does not, it is created. ensureIndex is intelligent and does not repeat transmissions to the server; thus it is safe to call it many times in your code, for example, adjacent to every insert operation. In the above example we use a new function, fromjson. fromjson converts a JSON string to a BSONObj. This is sometimes a convenient way to specify BSON. Alternatively, we could have written:
SortingLet's now make the results from printIfAge sorted alphabetically by name. To do this, we change the query statement from:
to
Here we have used Query::sort() to add a modifier to our query expression for sorting. UpdatingUse the update() method to perform a database update . For example the following update in the mongo shell :
is equivalent to the following C++ code:
ExampleA simple example illustrating usage of BSON arrays and the "$nin" operator is available here . Further ReadingThis overview just touches on the basics of using Mongo from C++. There are many more capabilities. For further exploration:
|