bson对象的解析

来源:互联网 发布:win7桌面时钟软件 编辑:程序博客网 时间:2024/05/20 14:26
 bson query[1];         //声明bson 变量
 bson_init(query);      //初始化 开始构造 query
 bson_append_start_object(query, "$query"); //给 query 追加一个 新的 BSON 对象
 bson_append_finish_object(query);          //结束
 bson_append_start_object(query, "$orderby");
 bson_append_int(query, "load", 1);         //追加一个 int 类型的值
 bson_append_finish_object(query);          //结束
 bson_finish(query);                        //结束构造 query
 string tableName = "db_gss.tbl_robot_stats";
 int result = 0;
 CCursorStoreResult *cursorStoreResult = mongodbConnection.mongodbFind(tableName, query, 1, 0).release(); //查询满足 query 的数据 并返回结果集
 if (!cursorStoreResult) {
TRACE(1, "mongodb find error, with tables name: "<<tableName);
result = -1;
 } else {
result = -2;
while (cursorStoreResult->fetchRow()) {            //取出一行数据
 bson_iterator bi;                                //定义BSON 类型的迭代器
 if (!cursorStoreResult->getField("iplist", bi)) { //给bi赋值,让 bi 指向 索引为 "iplist" 的数据 内部调用了 bson_find()函数
TRACE(LOG_ERROR, "getField iplist error, table name: "<<tableName);
result = -3;
break;
 }
 bson_iterator subit[1];      //定义一个子迭代器 
 bson_iterator nInterat[1];
 bson_iterator_subiterator(&bi, subit);  //用于遍历bi迭代器下面的数据(应该是两者迭代器的步长不一样)
 // [ {   "ip" : "115.231.78.14" },{ "ip" : "101.69.207.144" } ]
 //get array list element one by one
 while (bson_iterator_more(subit)) {          //用subit 遍历 数据
if (bson_iterator_next(subit)!=BSON_EOO) { //循环取出数据
 bson sub_Object[1];
 Json::Value jsonIp;
 bson_iterator_subobject_init(subit, sub_Object, 1); //得到subit指向的数据, 1 代表 重复使用sub_Object 必须 销毁
 //comment out the following bson_find could show the expected result
 if (bson_find(nInterat, sub_Object, "ip") == BSON_EOO) //找出sub_Object下面 “ip”对应的值
 {
TRACE(LOG_ERROR, "getField ip=>ip error, table name: "<<tableName);
result = -4;
break;
 }
 jsonIp["ip"]    = bson_iterator_string(nInterat);
 robotip.append(jsonIp);
 bson_destroy(sub_Object); //销毁 sub_Object
}
 }
 int32_t port;
 cursorStoreResult->getField("robot_port", port);
 cursorStoreResult->getField("robot_id", robotid);
 robotport = port;
 result = 0;
 break;
}
 }
 bson_destroy(query);     //销毁
 delete cursorStoreResult;//销毁
 return result;
原创粉丝点击