mongodb C++调用简单DEMO
简单粗暴,直接扔代码!!
main.cpp
/*
* file : main.cpp
* directory : example for mongodb using in c++
* author : HotVC
* Official statement:
* http://docs.mongodb.org/ecosystem/drivers/cpp-to-sql-to-mongo-shell/
*/
#include<iostream>
#include"mongo/client/dbclient.h"
#include <stdlib.h>
#include <stdio.h>
#include <boost/foreach.hpp>
using namespace std;
using namespace mongo;
#define CONNECT_STRING "mongodb://localhost:27017"
#define DATA_COLLECTION "testdb"
#define DATA_TABLE "student"
ConnectionString g_csConn;
string g_strErr;
//boost::scoped_ptr<DBClientBase> g_spConnBase;
DBClientBase *g_spConnBase;
//
int main() {
//call the client initialize function to use the BSON library.
mongo::client::GlobalInstance instance;
if (!instance.initialized()) {
std::cout << "failed to initialize the client driver: " << instance.status() << std::endl;
return EXIT_FAILURE;
}
g_csConn = ConnectionString::parse(CONNECT_STRING, g_strErr);
if (!g_csConn.isValid())
{
cout << "Error parsing connection string " << CONNECT_STRING << ": " << g_strErr << endl;
return EXIT_FAILURE;
}
cout << "g_csConn is right" <<endl;
g_spConnBase = g_csConn.connect(g_strErr);
// foreach dataBase
list<string> lDataBase = g_spConnBase->getDatabaseNames();
BOOST_FOREACH(string strIterator, lDataBase)
{
cout << "DataBase Name is : "<< strIterator <<endl;
}
// foreach collections
list<string> lCollections = g_spConnBase->getCollectionNames(DATA_COLLECTION);
BOOST_FOREACH(string strIterator, lCollections)
{
cout << "collections Name is : "<< strIterator <<endl;
}
cout << "========================&#