C# 中的 MongoDB 地理空间索引

2024-04-06

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

Code:

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);
    }
}

下面的示例是 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;
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C# 中的 MongoDB 地理空间索引 的相关文章

随机推荐

  • 将参数传递给 std::thread 包装器

    我想实现一个小型线程包装器 它提供线程是否仍处于活动状态或者线程是否已完成其工作的信息 为此 我需要将线程类要执行的函数及其参数传递给另一个函数 我有一个简单的实现 应该可以工作 但无法编译它 而且我不知道该怎么做才能使它工作 这是我的代码
  • Symfony2 - 获取 TWIG 模板中的当前 URL 或路由?

    我的路线是 admin path admin defaults controller CatalogWebBundle Admin admin 如何在 PHP 模板中获取路由名称 获取当前 URL request gt getRequest
  • Postgres 中左连接分页

    Summary 我的数据库中有需要在客户端显示的数据 到目前为止 它还没有被分页 但现在数据已经增长到明显减慢连接速度的程度 所以我想分页它 Setup 客户端我正在使用 DataTables 服务器端我使用 F 数据库是postgres
  • 一段时间后未调用 CLLocationManager didUpdateToLocation

    我正在尝试记录用户随时间的位置 如果用户在移动 则它可以正常工作 并且委托方法 didUpdateToLocation 会被可靠地调用 但是 如果用户静止并且应用程序在后台运行 那么在一段时间后 将不再调用委托方法 要重新启动它 需要将该应
  • 带参数的 Typescript 工厂模式

    我目前在我的项目中使用工厂模式 下面是最小的可重现代码 class A constructor public name string class B constructor public age number public address
  • Internet Explorer 中的 JavaScript 正则表达式问题

    我正在尝试使用正则表达式拆分 Javascript 中的字符串 我的代码如下 var status This is a test http yfrog com 5y6eruj var regexp http yfrog com w 0 1
  • 如何制作字典扩展方法?

    我正在尝试写一个Dictionary独立于键 值数据类型工作的扩展 我尝试通过使用object数据类型 假设它适用于任何类型 My code public static class DictionaryExtensionsClass pub
  • 具有 Spring Boot 应用程序的 docker Secret 无法在 docker swarm 模式/run/secrets 下工作

    我正在尝试设置 MySQL 容器和 Spring Boot 应用程序的数据库密码的环境变量 该密码通常在 docker 秘密中声明 echo db secured password docker secret create secret 这
  • 如何统计有向图中所有可达节点?

    有一个有向图 可能包含环 每个节点上都有一个值 如何得到每个节点的可达值之和 例如 在下图中 节点 1 的可达和为 2 3 4 5 6 7 27 节点 2 的可达总和为 4 5 6 7 22 我的解决方案 要得到所有节点的总和 我认为时间复
  • REALM、SQLITE、FCM 数据库之间的区别[关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 REALM SQLITE FCM数据库之间的区别 REALM SQLITE FCM 数据库之间的主要区别是什么 为什么我更喜欢这个数据
  • 何时何地使用 Lambda?

    我试图理解为什么我们真的需要 ruby 中的 lambda 或 proc 或任何其他语言 method def add a b c a b end using proc def add proc a b f Proc new x y x y
  • ds.Tables[0].Select() 代表什么

    博士在这里得到什么 DataRow dr objds Tables 0 Select ProcessName tnProcName Text 我得到的是 dr System Data DataRow 4 而不是单独的行 在 dr 中 现在由
  • IE9:我的网站上的 CPU 利用率始终较低

    我使用 JQuery 和许多拖放元素开发了一个网站 效果非常好 然而 在 IE9 上 当动态加载 使用 load 并显示大量拖放元素时 浏览器总是消耗少量 CPU 10 用于刷新 即使没有任何内容用户长时间不触摸鼠标或滚动页面即可完成此操作
  • 将 Google 域链接到 Amazon ec2 服务器

    我正在使用 Amazon EC2 实例来为 node js 应用程序提供服务 我最近通过以下方式购买了域名谷歌域名 https domains google com我想使用该域名来访问我的 node js 应用程序 Google Domai
  • 在AWS SNS(简单通知服务)电子邮件通知中发送html内容

    我在用AWS SNS 简单通知服务 发送电子邮件通知 在电子邮件的内容中 我必须以表格形式表示数据 目前我正在使用简单的文本字符串打印表格 但有格式问题当通过手机和平板电脑等较小屏幕设备访问电子邮件时 表格数据根本无法解释 我希望使用 ht
  • “结构细化中的参数类型可能不会引用该细化之外定义的抽象类型”

    当我编译时 object Test extends App implicit def pimp V xs Seq V new def dummy x V x I get fsc d aoeu go scala go scala 3 err
  • UITableView 中的图像不断重新加载,并且滚动时错误的图像会闪烁

    我创建了一个 UITableView 它根据 URL 请求填充每个单元格 我使用 dispatch queue 来防止 UItableView 冻结 由于某种原因 当我滚动 UITableView 时 图像会闪烁并消失 并填充错误的单元格一
  • 如何循环遍历表来查找数据集?

    我必须找到订单生命周期的时间差 以分钟为单位 即每个订单从收到订单 活动 ID 1 到键入 2 到打印 3 到交付 4 的时间 for eg 我完全迷失了我应该采取哪种方法 用例或 if then 语句 类似于 for every 循环遍历
  • 如何获取多列的groupby总和

    我有一个 pandas 数据框 如下所示 index col1 col2 col3 col4 col5 0 a c 1 2 f 1 a c 1 2 f 2 a d 1 2 f 3 b d 1 2 g 4 b e 1 2 g 5 b e 1
  • C# 中的 MongoDB 地理空间索引

    我一直在尝试使用 C 官方驱动程序创建和查询 MongoDB 但一次又一次地遇到同样的问题 问题是如何用地理信息创建数据 我只是找不到答案 Code MongoUrl url new MongoUrl mongodb xxx xx x xx