Use Mongo in C ++ to perform count and distinct operations

Source: Internet
Author: User

Assume that the server has the Mongo database MyDB, including the MyTable table and the fields "IP" and "Date", which respectively record the Client IP address and access time for accessing the service, account User with access permission to the MyTable table, password 123456
 
(1) create a connection
 
 
Mongo: DBClientConnection pConn = new mongo: DBClientConnection;
String strErr;
PConn-> connect ("127.0.0.1", strErr)
PConn-> auth ("MyDB", "User", "123456", strErr );
 
 
(2) count operation
// Count the number of records of the specified date in the range DateStart and DateEnd
// "$ Gte" is a comparison operator of Mongo >=, "$ lte" is <=, "$ gt" is>, and "$ lt" is <
 
 
Int64 DateStart = 1315014772, DateEnd = 1317606772;
Unsigned int64 u64Count = pConn-> count ("MyTable ",
BSON ("Date" <BSON ("$ gte" <DateStart <"$ lte" <DateEnd )));
 
 
(3) distinct operation
// Number of all different IP addresses in the statistical table
 
 
Bo bobj;
PConn-> runCommand ("MyDB ",
BSON ("distinct" <"MyTabel" <"key" <"IP", bobj ));
Vector <be> vecbe = obj. getField ("values"). Array ();
Size_t szIPCount = vecbe. size ();
 
// View the specific IP Address
Vector <string> vecIP;
For (size_t I = 0; I <szIPCount; I ++)
{
VecIP. push_back (vecbe [I]. String ());
}
 
// The number of different client IP addresses that access the service in a certain period of time according to the condition statistics
 
 
PConn-> runCommand ("MyDB ",
BSON ("distinct" <"MyTabel" <"key" <"IP"
<"Query" <BSON ("Date" <BSON ("$ gte" <DateStart <"$ lte" <DateEnd), obj );
 

From the shellching Column

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.