C# 访问mongodb数据库

1.引用四个mongodb动态库MongoDB.Bson.dll,MongoDB.Driver.Core.dll,MongoDB.Driver.dll,MongoDB.Driver.Legacy.dll

    /// <summary>
    /// 从mongodb数据库获取谷歌影像
    /// </summary>
    public class MongoDBReaderHelper
    {
        /// <summary>
        /// 链接字符串
        /// </summary>
        private string conn = "mongodb://127.0.0.1:27017";
        /// <summary>
        /// 指定的数据库
        /// </summary>
        private string dbName = "Level1-Level14";
        /// <summary>
        /// Mongo客户端
        /// </summary>
        private MongoClient client;
        /// <summary>
        /// 当前操作数据库
        /// </summary>
        protected IMongoDatabase database;
        /// <summary>
        /// 当前操作的数据库表
        /// </summary>
        protected IMongoCollection<Tiled> collection;


        private Dictionary<string, IMongoCollection<Tiled>> CollectionList = new Dictionary<string, IMongoCollection<Tiled>>();
        public bool InitMongoDB(string connectionString)
        {
            this.conn = connectionString;
            client = new MongoClient(conn);
            if (client == null)
            {
                 //cons .Show("服务器连接失败");
                Console.WriteLine("mongodb数据库连接失败");
                return false;
            }

            database = client.GetDatabase(dbName);
            collection = database.GetCollection<Tiled>("Titles");//数据库表
            this.CollectionList.Add(dbName, collection);
            Console.WriteLine("mongodb数据库连接成功");

            return true;
        }


        /// <summary>
        /// 获取瓦片
        /// </summary>
        /// <param name="key">Key值:4-6-11</param>
        /// <param name="collection"></param>
        /// <returns>把图片输出到本地</returns>
        protected async Task<byte[]> _GetTiled(string key, IMongoCollection<Tiled> collection)
        {
            if (collection == null) return null;
            var filter = Builders<Tiled>.Filter.Eq("_id", key);
            Task<Tiled> document = collection.Find<Tiled>(filter).FirstOrDefaultAsync();
            Tiled tiled = await document;
            //if (tiled != null)
            //{
            //    string filename = tiled.Key + ".jpg";
            //    byte[] img = tiled.ByteImg;
            //    using (FileStream fs = new FileStream(filename, FileMode.CreateNew))
            //    {
            //        fs.Write(img, 0, img.Length);
            //        fs.Close();
            //    }
            //}

            return tiled.ByteImg;
        }

        /// <summary>
        /// 获取瓦片
        /// </summary>
        /// <param name="key">Key值:4-6-11</param>
        /// <param name="collection"></param>
        /// <returns>把图片输出到本地</returns>
        public async Task<byte[]> GetTiled(string key)
        {
            string[] tmplist = key.Split('-');
            if(tmplist.Length!=3)
            {
                Console.WriteLine("Tile关键字不符合要求" + key);
                return null;
            }
            int level = 0;
            int x = 0;
            int y = 0;
            if(!int.TryParse(tmplist[0],out level))
            {
                Console.WriteLine("Tile级别不符合要求" + key);
                return null;
            }
            if (!int.TryParse(tmplist[1], out x))
            {
                Console.WriteLine("X不符合要求" + key);
                return null;
            }
            if (!int.TryParse(tmplist[2], out y))
            {
                Console.WriteLine("Y不符合要求" + key);
                return null;
            }

            return await _GetTiled(key, GetCollection(level,x,y));
        }
        private IMongoCollection<Tiled> GetCollection(int level,int x,int y)
        {
            string dbname = LevelToDBName(level);
            if(dbname=="")
            {
                return null;
            }
            string tablename = LXYToTableName(level, x, y);

            string key = string.Format("{0}_{1}", dbname, tablename);

            Console.WriteLine(string.Format("{0},{1},{2}-->{3}",level,x,y,key));
            if (!this.CollectionList.ContainsKey(key))
            {
                database = client.GetDatabase(key);
                if(database==null)
                {
                    return null;
                }
                collection = database.GetCollection<Tiled>(tablename);//数据库表
                this.CollectionList.Add(key, collection); 
            }
            return this.CollectionList[key];
        }

        private string LXYToTableName(int level, int x, int y)
        {
            string ret = "Titles";

            if(level>=15)
            {
                int xindex = x /(int) (Math.Pow(2, 15));
                int yindex = y / (int)(Math.Pow(2, 15));

                int n = xindex * (int)Math.Pow(2, level - 15) + yindex+1;

                ret = string.Format("Titles{0:D2}", n);

            }
            return ret;
        }
        private string LevelToDBName(int level)
        {
            if(level>=1&&level<=14)
            {
                return "Level1-Level14";
            }
            else if(level>14)
            {
                return string.Format("Level{0}", level);
            }
            return "";
        }
    }

    /// <summary>
    /// 对应数据库中的数据表
    /// </summary>
    public class Tiled
    {
        //public UInt64 Id { get; set; }
        /// <summary>
        /// 图片流
        /// </summary>
        public byte[] ByteImg { get; set; }
        [BsonId]
        public string Key { get; set; }
    }
}
View Code
原文地址:https://www.cnblogs.com/HouseNumber1703/p/5842313.html