C# C语言中的MongoDB地理空间索引#

C# C语言中的MongoDB地理空间索引#,c#,mongodb,geocoding,geospatial,mongodb-.net-driver,C#,Mongodb,Geocoding,Geospatial,Mongodb .net Driver,我一直在尝试开始,但一次又一次地尝试用C#官方驱动程序创建和查询MongoDB,却遇到了同样的困难。问题是如何使用地理信息创建数据。我只是没有找到答案 代码: 下面的例子是C#(注意数组中的顺序很重要,即经度,纬度-遵循更符合逻辑的x,y顺序,而不是更常用的形式,其中经度在经度之前): 1.)首先,您的班级需要: public double[] Location { get; set; } public double Latitude { get { return _latitude;

我一直在尝试开始,但一次又一次地尝试用C#官方驱动程序创建和查询MongoDB,却遇到了同样的困难。问题是如何使用地理信息创建数据。我只是没有找到答案

代码:

下面的例子是C#(注意数组中的顺序很重要,即经度,纬度-遵循更符合逻辑的x,y顺序,而不是更常用的形式,其中经度在经度之前):

1.)首先,您的班级需要:

public double[] Location { get; set; }

public double Latitude
{
    get { return _latitude; }
    set
    {
        Location[1] = value;
        _latitude = value;
    }
}

public double Longitude
{
    get { return _longitude; }
    set
    {
        Location[0] = value;
        _longitude = value;
    }
}

public MyClass()
{
    Location = new double[2];
}
2.)下面是一些代码,让您开始使用官方C#驱动程序,并使用地理索引进行插入:

    /// <summary>
    /// Inserts object and creates GeoIndex on collection (assumes TDocument is a class
    /// containing an array double[] Location where [0] is the x value (as longitude)
    /// and [1] is the y value (as latitude) - this order is important for spherical queries.
    /// 
    /// Collection name is assigned as typeof(TDocument).ToString()
    /// </summary>
    /// <param name="dbName">Your target database</param>
    /// <param name="data">The object you're storing</param>
    /// <param name="geoIndexName">The name of the location based array on which to create the geoIndex</param>
    /// <param name="indexNames">optional: a dictionary containing any additional fields on which you would like to create an index
    /// where the key is the name of the field on which you would like to create your index and the value should be either SortDirection.Ascending
    /// or SortDirection.Descending. NOTE: this should not include geo indexes! </param>
    /// <returns>void</returns>
    public static void MongoGeoInsert<TDocument>(string dbName, TDocument data, string geoIndexName, Dictionary<string, SortDirection> indexNames = null)
    {
        Connection connection = new Connection(dbName);
        MongoCollection collection = connection.GetMongoCollection<TDocument>(typeof(TDocument).Name, connection.Db);
        collection.Insert<TDocument>(data);
        /* NOTE: Latitude and Longitude MUST be wrapped in separate class or array */
        IndexKeysBuilder keys = IndexKeys.GeoSpatial(geoIndexName);
        IndexOptionsBuilder options = new IndexOptionsBuilder();
        options.SetName("idx_" + typeof(TDocument).Name);
        // since the default GeoSpatial range is -180 to 180, we don't need to set anything here, but if
        // we wanted to use something other than latitude/longitude, we could do so like this:
        // options.SetGeoSpatialRange(-180.0, 180.0);

        if (indexNames != null)
        {
            foreach (var indexName in indexNames)
            {
                if (indexName.Value == SortDirection.Decending)
                {
                    keys = keys.Descending(indexName.Key);
                }
                else if (indexName.Value == SortDirection.Ascending)
                {
                    keys = keys.Ascending(indexName.Key);
                }
            }
        }

        collection.EnsureIndex(keys, options);

        connection.Db.Server.Disconnect();
    }


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Bson;
using MongoDB.Driver;

namespace MyMongo.Helpers
{
    public class Connection
    {
        private const string DbName = "";
        private const string Prefix = "mongodb://";
        //private const string Server = "(...):27017/";
        private const string Server = "localhost:27017/";
        private const string PassWord = "";
        private const string UserName = "";
        private const string Delimeter = "";
        //if using MongoHQ
        //private const string Delimeter = ":";
        //private const string Prefix = "mongodb://";
        //private const string DbName = "(...)";
        //private const string UserName = "(...)";
        //private const string Server = "@flame.mongohq.com:(<port #>)/";
        //private const string PassWord = "(...)";
        private readonly string _connectionString = string.Empty;

        public MongoDatabase Db { get; private set; }
        public MongoCollection Collection { get; private set; }

        public Connection()
        {
            _connectionString = Prefix + UserName + Delimeter + PassWord + Server + DbName;
        }

        public Connection(string dbName)
        {
            _connectionString = Prefix + UserName + Delimeter + PassWord + Server + DbName;
            Db = GetDatabase(dbName);
        }

        //mongodb://[username:password@]hostname[:port][/[database][?options]]
        public MongoDatabase GetDatabase(string dbName)
        {
            MongoServer server = MongoServer.Create(_connectionString);
            MongoDatabase database = server.GetDatabase(dbName);
            return database;
        }

        public MongoCollection<TDocument> GetMongoCollection<TDocument>(string collectionName, MongoDatabase db, SafeMode safeMode = null)
        {
            if (safeMode == null) { safeMode = new SafeMode(true); }
            MongoCollection<TDocument> result = db.GetCollection<TDocument>(collectionName, safeMode);
            return result;
        }
    }
}
//
///在集合上插入对象并创建GeoIndex(假定TDocument是一个类
///包含数组double[]位置,其中[0]是x值(作为经度)
///[1]是y值(作为纬度)-这个顺序对于球形查询很重要。
/// 
///集合名称被指定为typeof(TDocument).ToString()
/// 
///您的目标数据库
///您正在存储的对象
///要创建地理索引的基于位置的数组的名称
///可选:包含要在其上创建索引的任何附加字段的字典
///其中,键是要在其上创建索引的字段的名称,值应为SortDirection.Ascending
///或SortDirection.Descending。注意:这不应包括地理索引!
///空虚
public static void mongooinsert(字符串dbName、TDocument数据、字符串geoIndexName、Dictionary indexNames=null)
{
连接=新连接(dbName);
MongoCollection collection=connection.GetMongoCollection(typeof(TDocument).Name,connection.Db);
收集.插入(数据);
/*注意:纬度和经度必须包装在单独的类或数组中*/
IndexKeysBuilderKeys=IndexKeys.GeoSpatial(geoIndexName);
IndexOptionsBuilder选项=新建IndexOptionsBuilder();
options.SetName(“idx_uu3;”+typeof(TDocument.Name);
//由于默认地理空间范围为-180到180,因此不需要在此处设置任何内容,但如果
//我们想使用除纬度/经度以外的东西,我们可以这样做:
//选项。设置地理空间范围(-180.0,180.0);
if(indexNames!=null)
{
foreach(indexNames中的变量indexName)
{
if(indexName.Value==SortDirection.Decenting)
{
keys=keys.Descending(indexName.Key);
}
else if(indexName.Value==SortDirection.升序)
{
keys=keys.Ascending(indexName.Key);
}
}
}
集合。EnsureIndex(键、选项);
connection.Db.Server.Disconnect();
}
使用制度;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用MongoDB.Bson;
使用MongoDB.Driver;
名称空间MyMongo.Helpers
{
公共类连接
{
私有常量字符串DbName=“”;
private const string Prefix=“mongodb://”;
//private const string Server=“(…):27017/”;
private const string Server=“localhost:27017/”;
private const string PassWord=“”;
private const string UserName=“”;
私有常量字符串Delimeter=“”;
//如果使用MongoHQ
//private const string Delimeter=“:”;
//private const string Prefix=“mongodb://”;
//私有常量字符串DbName=“(…)”;
//私有常量字符串UserName=“(…)”;
//private const string Server=“@flame.mongohq.com:()/”;
//private const string PassWord=“(…)”;
私有只读字符串_connectionString=string.Empty;
公共MongoDatabase数据库{get;private set;}
公共MongoCollection集合{get;private set;}
公共连接()
{
_connectionString=Prefix+UserName+Delimeter+PassWord+Server+DbName;
}
公共连接(字符串dbName)
{
_connectionString=Prefix+UserName+Delimeter+PassWord+Server+DbName;
Db=GetDatabase(dbName);
}
//mongodb://[username:password@]主机名[:端口][/[database][?选项]]
公共MongoDatabase GetDatabase(字符串dbName)
{
MongoServer server=MongoServer.Create(_connectionString);
MongoDatabase database=server.GetDatabase(dbName);
返回数据库;
}
公共MongoCollection GetMongoCollection(string collectionName,MongoDatabase db,SafeMode SafeMode=null)
{
如果(safeMode==null){safeMode=new safeMode(true);}
MongoCollection结果=db.GetCollection(collectionName,safeMode);
返回结果;
}
}
}

经过查找和搜索,我在这里找到了答案:

这将与我的第一段代码一起阅读,因为这将修复它

  MongoCollection<BsonDocument> places =
               database.GetCollection<BsonDocument>("places");

            BsonDocument[] batch = {
                                       new BsonDocument { { "name", "Bran" }, { "loc", new BsonArray(new[] { 10, 10 }) } },
                                       new BsonDocument { { "name", "Ayla" }, { "loc", new BsonArray(new[] { 0, 0 }) } }
            };

            places.InsertBatch(batch);

            places.EnsureIndex(IndexKeys.GeoSpatial("loc"));

            var queryplaces = Query.WithinCircle("loc", 5, 5, 10);
            var cursor = places.Find(queryplaces);
            foreach (var hit in cursor)
            {
                Console.WriteLine("in circle");
                foreach (var VARIABLE in hit)
                {
                    Console.WriteLine(VARIABLE.Value);

                }
            }
MongoCollection地点=
数据库。GetCollection(“地点”);
B第[]批单据={
新文件{{“name”,“Bran”},{“loc”,新文件{10,10}},
新BsonDocument{{“name”,“Ayla”},{“loc”,新BsonArray(新[]{0,0})}
};
位置。插入批次(批次);
地点。确保索引(索引键。地理空间(“loc”);
var queryplaces=Query.withincrcle(“loc”,5,5,10);
var cursor=places.Find(queryplaces);
foreach(游标中的var命中)
{
控制台。写线(“圈内”);
foreach(hit中的var变量)
{
Console.WriteLine(变量.Value);
}
}
作为澄清的一点:p
public double[] Location { get; set; }

public double Latitude
{
    get { return _latitude; }
    set
    {
        Location[1] = value;
        _latitude = value;
    }
}

public double Longitude
{
    get { return _longitude; }
    set
    {
        Location[0] = value;
        _longitude = value;
    }
}

public MyClass()
{
    Location = new double[2];
}
    /// <summary>
    /// Inserts object and creates GeoIndex on collection (assumes TDocument is a class
    /// containing an array double[] Location where [0] is the x value (as longitude)
    /// and [1] is the y value (as latitude) - this order is important for spherical queries.
    /// 
    /// Collection name is assigned as typeof(TDocument).ToString()
    /// </summary>
    /// <param name="dbName">Your target database</param>
    /// <param name="data">The object you're storing</param>
    /// <param name="geoIndexName">The name of the location based array on which to create the geoIndex</param>
    /// <param name="indexNames">optional: a dictionary containing any additional fields on which you would like to create an index
    /// where the key is the name of the field on which you would like to create your index and the value should be either SortDirection.Ascending
    /// or SortDirection.Descending. NOTE: this should not include geo indexes! </param>
    /// <returns>void</returns>
    public static void MongoGeoInsert<TDocument>(string dbName, TDocument data, string geoIndexName, Dictionary<string, SortDirection> indexNames = null)
    {
        Connection connection = new Connection(dbName);
        MongoCollection collection = connection.GetMongoCollection<TDocument>(typeof(TDocument).Name, connection.Db);
        collection.Insert<TDocument>(data);
        /* NOTE: Latitude and Longitude MUST be wrapped in separate class or array */
        IndexKeysBuilder keys = IndexKeys.GeoSpatial(geoIndexName);
        IndexOptionsBuilder options = new IndexOptionsBuilder();
        options.SetName("idx_" + typeof(TDocument).Name);
        // since the default GeoSpatial range is -180 to 180, we don't need to set anything here, but if
        // we wanted to use something other than latitude/longitude, we could do so like this:
        // options.SetGeoSpatialRange(-180.0, 180.0);

        if (indexNames != null)
        {
            foreach (var indexName in indexNames)
            {
                if (indexName.Value == SortDirection.Decending)
                {
                    keys = keys.Descending(indexName.Key);
                }
                else if (indexName.Value == SortDirection.Ascending)
                {
                    keys = keys.Ascending(indexName.Key);
                }
            }
        }

        collection.EnsureIndex(keys, options);

        connection.Db.Server.Disconnect();
    }


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Bson;
using MongoDB.Driver;

namespace MyMongo.Helpers
{
    public class Connection
    {
        private const string DbName = "";
        private const string Prefix = "mongodb://";
        //private const string Server = "(...):27017/";
        private const string Server = "localhost:27017/";
        private const string PassWord = "";
        private const string UserName = "";
        private const string Delimeter = "";
        //if using MongoHQ
        //private const string Delimeter = ":";
        //private const string Prefix = "mongodb://";
        //private const string DbName = "(...)";
        //private const string UserName = "(...)";
        //private const string Server = "@flame.mongohq.com:(<port #>)/";
        //private const string PassWord = "(...)";
        private readonly string _connectionString = string.Empty;

        public MongoDatabase Db { get; private set; }
        public MongoCollection Collection { get; private set; }

        public Connection()
        {
            _connectionString = Prefix + UserName + Delimeter + PassWord + Server + DbName;
        }

        public Connection(string dbName)
        {
            _connectionString = Prefix + UserName + Delimeter + PassWord + Server + DbName;
            Db = GetDatabase(dbName);
        }

        //mongodb://[username:password@]hostname[:port][/[database][?options]]
        public MongoDatabase GetDatabase(string dbName)
        {
            MongoServer server = MongoServer.Create(_connectionString);
            MongoDatabase database = server.GetDatabase(dbName);
            return database;
        }

        public MongoCollection<TDocument> GetMongoCollection<TDocument>(string collectionName, MongoDatabase db, SafeMode safeMode = null)
        {
            if (safeMode == null) { safeMode = new SafeMode(true); }
            MongoCollection<TDocument> result = db.GetCollection<TDocument>(collectionName, safeMode);
            return result;
        }
    }
}
  MongoCollection<BsonDocument> places =
               database.GetCollection<BsonDocument>("places");

            BsonDocument[] batch = {
                                       new BsonDocument { { "name", "Bran" }, { "loc", new BsonArray(new[] { 10, 10 }) } },
                                       new BsonDocument { { "name", "Ayla" }, { "loc", new BsonArray(new[] { 0, 0 }) } }
            };

            places.InsertBatch(batch);

            places.EnsureIndex(IndexKeys.GeoSpatial("loc"));

            var queryplaces = Query.WithinCircle("loc", 5, 5, 10);
            var cursor = places.Find(queryplaces);
            foreach (var hit in cursor)
            {
                Console.WriteLine("in circle");
                foreach (var VARIABLE in hit)
                {
                    Console.WriteLine(VARIABLE.Value);

                }
            }