本文使用官方C# Driver,实现在MongoDB中存储,查询空间数据(矢量) 空间数据的存储 本例中,从一个矢量文件(shapefile格式)中读取矢量要素空间信息以及属性表,并写入到MongoDB中去,其中读取shapefile文件以及将空间信息转成json的功能通过Ogr库实现 [csh
本文使用官方C# Driver,实现在MongoDB中存储,查询空间数据(矢量)
空间数据的存储
本例中,从一个矢量文件(shapefile格式)中读取矢量要素空间信息以及属性表,并写入到MongoDB中去,其中读取shapefile文件以及将空间信息转成json的功能通过Ogr库实现
[csharp] view plaincopyprint?01.//打开MongoDB的Collection
02. MongoDatabase db = server.GetDatabase(“aa”);
03. MongoCollection colSheng = db.GetCollection(“sheng”);
04. //使用Ogr库打开Shapefile文件
05. DataSource ds = Ogr.Open(@”c:\temp\sheng.shp”, 0);
06. Layer lyr = ds.GetLayerByIndex(0);
07. //读取要素数量和字段数量
08. int feaCount = lyr.GetFeatureCount(0);
09. int fieldCount = lyr.GetLayerDefn().GetFieldCount();
10. //读取所有字段名
11. List fieldNames =new List();
12. for (int i = 0; i < fieldCount; i++)
13. {
14. fieldNames.Add(lyr.GetLayerDefn().GetFieldDefn(i).GetName());
15. }
16. //循环将所有要素添加到MongoDB中
17. for (int i = 0; i < feaCount; i++)
18. {
19. //使用Ogr库将矢量要素的空间信息转成Json格式
20. Feature fea = lyr.GetFeature(i);
21. Geometry geo = fea.GetGeometryRef();
22. string json = geo.ExportToJson(null);
23.
24. BsonDocument doc = new BsonDocument();
25.
26. //将Json格式的空间信息存到Collection中
27. //BsonValue bs = BsonValue.Create(json); //这种方法是不可以的,添加到库里之后无法使用空间查询语句查询
28. BsonValue bs2 = BsonDocument.Parse(json); //这种方法才是正确的
29. //doc.Add(new BsonElement(“geom”, bs));
30. doc.Add(new BsonElement(“geo”,bs2));
31. //通过循环将所有字段的属性信息存入Collection中
32. for (int j = 0; j < fieldCount; j++)
33. {
34. string tmpFieldVal = fea.GetFieldAsString(j);
35. doc.Add(new BsonElement(fieldNames[j],tmpFieldVal));
36. }
37. var res = colSheng.Insert(doc);
38. }
//打开MongoDB的Collection
MongoDatabase db = server.GetDatabase(“aa”);
MongoCollection colSheng = db.GetCollection(“sheng”);
//使用Ogr库打开Shapefile文件
DataSource ds = Ogr.Open(@”c:\temp\sheng.shp”, 0);
Layer lyr = ds.GetLayerByIndex(0);
//读取要素数量和字段数量
int feaCount = lyr.GetFe本文来源gao.dai.ma.com搞@代*码(网$atureCount(0);
int fieldCount = lyr.GetLayerDefn().GetFieldCount();
//读取所有字段名
List fieldNames =new List();
for (int i = 0; i < fieldCount; i++)
{
fieldNames.Add(lyr.GetLayerDefn().GetFieldDefn(i).GetName());
}
//循环将所有要素添加到MongoDB中
for (int i = 0; i < feaCount; i++)
{
//使用Ogr库将矢量要素的空间信息转成Json格式
Feature fea = lyr.GetFeature(i);
Geometry geo = fea.GetGeometryRef();
string json = geo.ExportToJson(null);
BsonDocument doc = new BsonDocument();
//将Json格式的空间信息存到Collection中
//BsonValue bs = BsonValue.Create(json); //这种方法是不可以的,添加到库里之后无法使用空间查询语句查询
BsonValue bs2 = BsonDocument.Parse(json); //这种方法才是正确的
//doc.Add(new BsonElement(“geom”, bs));
doc.Add(new BsonElement(“geo”,bs2));
//通过循环将所有字段的属性信息存入Collection中
for (int j = 0; j < fieldCount; j++)
{
string tmpFieldVal = fea.GetFieldAsString(j);
doc.Add(new BsonElement(fieldNames[j],tmpFieldVal));
}
var res = colSheng.Insert(doc);
}