假設:服務端有Mongo數據庫MyDB,其中有表MyTable,表中有字段"IP"和"Date"等,分別記錄了訪問本服務的客戶端IP和訪問時間,MyTable表訪問權限的賬號User,密碼123456
(1)創建連接
mongo::DBClientConnection pConn = new mongo::DBClientConnection;
string strErr;
pConn->connect("127.0.0.1", strErr)
pConn->auth("MyDB", "User", "123456", strErr);
(2)count運算
//統計該日期在區間DateStart和DateEnd內的記錄數量
//"$gte"為Mongo的比較操作符>=,"$lte"為<=,"$gt"為>,"$lt"為<
int64 DateStart = 1315014772, DateEnd = 1317606772;
unsigned int64 u64Count = pConn->count("MyTable",
BSON("Date" << BSON("$gte" << DateStart << "$lte" << DateEnd)));
(3)distinct運算
//統計表中所有不同IP的數量
bo bobj;
pConn->runCommand("MyDB",
BSON("distinct" << "MyTabel" << "key" <<"IP", bobj));
vector<be> vecbe = obj.getField("values").Array();
size_t szIPCount = vecbe.size();
//查看具體IP
vector<string> vecIP;
for(size_t i=0; i<szIPCount; i++)
{
vecIP.push_back(vecbe[i].String());
}
//根據條件統計,在某時間段內訪問服務的不同客戶端IP的數量
pConn->runCommand("MyDB",
BSON("distinct" << "MyTabel" << "key" << "IP"
<< "query" << BSON("Date" << BSON("$gte" << DateStart << "$lte" << DateEnd))), obj);
摘自 shellching的專欄