mongodb C++ examples

//example 1
#include <iostream>
#include "client/dbclient.h"

using namespace mongo;

int main() {

DBClientConnection conn;
BSONObj p = BSONObjBuilder().append("name", "Joe").append("age", 33).obj();

try {
conn.connect("localhost");
cout << "connected ok" << endl;
} catch( DBException &e ) {
cout << "caught " << e.what() << endl;
}

conn.insert("tutorial.persons", p);
conn.insert("tutorial.persons", p);
conn.insert("tutorial.persons", p);
return 0;
}

$g++ mongotest.cpp -I /usr/local/include/mongo /usr/local/lib/libmongoclient.a  -lboost_thread -lboost_filesystem -lboost_program_options

2. examples:


> db.mongodb.insert({"dbName": "343", hostPort: ["127.0.0.1:1001", "127.0.1.2:4000"]})  
    > db.mongodb.find()  
    { "_id" : ObjectId("4f97b77afdc44ff960010ce2"), "dbName" : "343", "hostPort" : [ "192.168.0.191:30000" ] }  
    { "_id" : ObjectId("4f97c3f3fdc44ff960010ce5"), "dbName" : "343", "hostPort" : [ "127.0.0.1:1001", "127.0.1.2:400  
    0" ] }  
    >
string mongodbCollection = "test.mongodb";  
    auto_ptr<mongo::DBClientCursor> cursor = c->query( mongodbCollection , mongo::BSONObj() );  
    int count = 0;  
    while ( cursor->more() ) {  
        count++;  
        mongo::BSONObj obj = cursor->next();  
        const char *pDbName = obj.getStringField("dbName");  
        mongo::BSONElement hostPortElement = obj.getField("hostPort");  
        if (!hostPortElement.eoo()   
                &&hostPortElement.type() == mongo::Array  
            )  
        {  
            vector<mongo::BSONElement> hostPorts = hostPortElement.Array();  
            for (vector<mongo::BSONElement>::iterator it = hostPorts.begin(); it != hostPorts.end(); ++it)  
            {  
                string temp;  
                it->Val(temp);  
                cout << temp.c_str() << endl;  
            }  
        }  
    }



db.test0.update( { "count" : { $gt : 1 } } , { $set : { "test2" :"OK"} } ); 只更新了第一条记录
db.test0.update( { "count" : { $gt : 3 } } , { $set : { "test2" :"OK"} },false,true ); 全更新了
db.test0.update( { "count" : { $gt : 4 } } , { $set : { "test5" :"OK"} },true,false ); 只加进去了第一条
db.test0.update( { "count" : { $gt : 5 } } , { $set : { "test5" :"OK"} },true,true ); 全加进去了
db.test0.update( { "count" : { $gt : 15 } } , { $inc : { "count" :1} },false,true );全更新了
db.test0.update( { "count" : { $gt : 10 } } , { $inc : { "count" :1} },false,false );只更新了第一条

http://www.mongodb.org/pages/viewpage.action?pageId=133415#C%2B%2BTutorial-Connecting




你可能感兴趣的:(mongodb C++ examples)