使用c++driver实现mongodb空间数据查询

来源:互联网 发布:nba比赛个人数据统计 编辑:程序博客网 时间:2024/05/16 12:31
        最近由于项目需求需要使用mongodb建立一个空间数据库,开始一直没有解决空间索引和空间查询的问题 过了很久才发现是数据格式的问题,mongodb并不会自动将json字符串数据转换为bson,需要手动转化,这是一个很有用的函数可以帮上忙,fromjson(),这个函数可以直接将json格式的数据转化为bson格式,
string json=pogeometry->exportToJson(); BSONObj tbson=fromjson(json);
         在建立索引的时候有一个问题一直没有解决,就是如果坐标超出了[-180,180)怎么办,这个值是mongodb的默认值,在shell操作时可以通过min,max对其索引范围进行修改,但是c++driver中似乎没有发现有关于min和max的代码,以下是我建立索引的代码:
if (i=="2d"){   m_DBClientConnection.ensureIndex(m_strdatabaseName+"."+m_strCollectionName,BSON("coordinates"<<"2d"),false,"",true,false,-1,0);}      else  {m_DBClientConnection.ensureIndex(m_strdatabaseName+"."+m_strCollectionName,BSON("coordinates"<<"2dsphere"),false,"",true,false,-1,0);}

          空间查询中,开始不知道对于不同的查询方式能够返回的值是有区别的,后来在操作手册上发现确实是有区别的,只有一部分操作能返回点线面,其他的只能返回点。

具体可以看这个网址http://docs.mongodb.org/manual/reference/operator/query-geospatial/。

         下面是查询的代码

 

void CVWMongoDatabase::query(double longitude_max,double longitude_min,double latitude_max,double latitude_min,int ntoreturn){BSONArray polygon = BSON_ARRAY(BSON_ARRAY(BSON_ARRAY(longitude_min<<latitude_min)<<BSON_ARRAY(longitude_min<<latitude_max)<<BSON_ARRAY(longitude_max<<latitude_max)<<BSON_ARRAY(longitude_max<<latitude_min)<<BSON_ARRAY(longitude_min<<latitude_min))); auto_ptr<DBClientCursor> cursor = m_DBClientConnection.query(m_strdatabaseName+"."+m_strCollectionName, BSON("value"<< BSON("$geoWithin"<<BSON("$geometry"<<BSON("type"<<"Polygon"<<"coordinates"<<polygon)))));while (cursor->more()){m_querysave.push_back(cursor->next().toString());}}void CVWMongoDatabase::query(double longitude,double latitude,int ntoreturn){BSONArray point = BSON_ARRAY(longitude<<latitude);auto_ptr<DBClientCursor> cursor = m_DBClientConnection.query(m_strdatabaseName+"."+m_strCollectionName, BSON("value"<< BSON("$near"<< point)));while (cursor->more()){m_querysave.push_back(cursor->next().toString());}}

0 0