当前位置:  开发笔记 > 编程语言 > 正文

C#中的MongoDB地理空间索引

如何解决《C#中的MongoDB地理空间索引》经验,为你挑选了1个好方法。

我一直试图开始尝试使用C#官方驱动程序创建和查询MongoDB,然后遇到同样的岩石.问题是如何使用地理信息创建数据.我只是没有找到答案.

码:

MongoUrl url = new MongoUrl("mongodb://xxx.xx.x.xx/mydb");
MongoServer server = MongoServer.Create(url);
MongoDatabase database = server.GetDatabase("mydb");

< - 这很好用

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

places.InsertBatch(batch);

< - 那部分是错误的

places.EnsureIndex(IndexKeys.GeoSpatial("loca"));
var queryplaces = Query.WithinCircle("loca", 0, 0, 11);
var cursor = places.Find(queryplaces);
foreach (var hit in cursor)
{
    foreach (var VARIABLE in hit)
    {
        Console.WriteLine(VARIABLE.Value);
    }
}

< - 我认为该部分应该显示两个文件,现在没有.一个简单的发现显示了它们.很高兴能得到一些帮助.



1> Jordan..:

下面的示例是在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#驱动程序并使用地理索引进行插入:

    /// 
    /// 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()
    /// 
    /// Your target database
    /// The object you're storing
    /// The name of the location based array on which to create the geoIndex
    /// 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! 
    /// void
    public static void MongoGeoInsert(string dbName, TDocument data, string geoIndexName, Dictionary indexNames = null)
    {
        Connection connection = new Connection(dbName);
        MongoCollection collection = connection.GetMongoCollection(typeof(TDocument).Name, connection.Db);
        collection.Insert(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:()/";
        //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 GetMongoCollection(string collectionName, MongoDatabase db, SafeMode safeMode = null)
        {
            if (safeMode == null) { safeMode = new SafeMode(true); }
            MongoCollection result = db.GetCollection(collectionName, safeMode);
            return result;
        }
    }
}

推荐阅读
爱唱歌的郭少文_
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有