Core3.1WebApi使用MongoDB

好久没有使用MongoDB了,重新测试,版本不一样之前很多方法都使用不了了,下面为部分测试,下次再来更新测试

测试中使用的命令

Core3.1WebApi使用MongoDB
// 新增读写的用户
db.createUser({
    user:fengge,
    pwd:FEG,
    roles:["readWrite"]
    })

//查询去掉 系统自带的objectid
db.student.find({},{_id:0});

//设置update  _id=2的 name=ffff
db.student.update({_d:2},[{$set:{name:ffff}}]);

// 查询包含有age的字段数据文档
db.student.find({age:{$exists:true}},{_id:0});

//写入当前时间
db.student.insert({_d:3,name:ww,birthday:new Date()});

//对所有的文档新增字段 tel
db.student.updateMany({},{$set:{tel:110}})

// 往一个数组中新增一个字段,原来是这样的:{_d:3,name:‘qq‘,books:[‘book1‘,book2‘]} => {_d:3,name:‘qq‘,books:[‘book1‘,book2‘,‘西游记‘]}
db.student.updateOne({_d:3},{$push:{books:西游记}})

// 和上面想法的操作 往一个数组中去掉一个字段,原来是这样的:{_d:3,name:‘qq‘,books:[‘book1‘,book2‘,‘西游记‘]} =>{_d:3,name:‘qq‘,books:[‘book1‘,book2‘]}
db.student.updateOne({_d:3},{$pull:{books:红楼梦}})
  
// 这个是不对的,会在book集合里面在新增一个集合
db.student.updateOne( { _d: 2 },{$push:{books:[西游记]}})

docker run -itd --name zrfmongo --restart=always -p 27017:27017 mongo
View Code

contract:

Core3.1WebApi使用MongoDB
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using ZRF.Models;

namespace ZRF.IContract
{
    public interface ImongoContract<T> where T : class, new()
    {
        #region mongodb数据库的链接操作配置
        IMongoCollection<T> GetCollection();
        /// <summary>
        /// 自定义 链接mongodb数据库字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dbname"></param>
        /// <param name="connectionStr"></param>
        /// <returns></returns>
        IMongoCollection<T> GetCollection(string dbname, string myconnectionStr = "");

        #endregion

        #region 新增操作
        bool InsertOne(T entity);

        Task<bool> InsertOneAsync(T entity);

        bool InsertMany(IEnumerable<T> entity);

        Task<bool> InsertManyAsync(IEnumerable<T> entity);

        #endregion

        #region 查询
        T FindOneByFunc(Expression<Func<T, bool>> func);

        Task<T> FindOneByFuncAsync(Expression<Func<T, bool>> func);

        IEnumerable<T> FindList(Expression<Func<T, bool>> func);

        Task<IEnumerable<T>> FindListAsync(Expression<Func<T, bool>> func);

        Task<PageData> FindListByPagenationwithOrderAsyn(Expression<Func<T, bool>> where, bool orderAscTrue, Expression<Func<T, object>> OrderBy, int pageIndex = 1, int pageSize = 20);
        Task<PageData> FindListByPagenationAsyn(Expression<Func<T, bool>> where, int pageIndex, int pageSize);

        /// <summary>
        /// 根据条件查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dics"></param>
        /// <returns></returns>
        Task<List<T>> QueryList(Dictionary<string, object> dics);


        #endregion

        #region 修改
        /// <summary>
        /// 编辑
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="id"></param>
        void Update(T entity, ObjectId id);

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        bool Update(T entity);

        #endregion

        #region 删除,备份
        ///// <summary>
        ///// 删除
        ///// remark:条件删除
        ///// </summary>
        ///// <typeparam name="T"></typeparam>
        ///// <param name="dics"></param>
        //public static void Delete<T>(Dictionary<string, object> dics) where T : class, new()
        //{
        //    var col = GetCollection<T>();

        //    var query = new QueryDocument(dics);

        //    var result = col.Remove(query);
        //}

        ///// <summary>
        ///// 删除
        ///// remark:根据ObjectId删除
        ///// </summary>
        ///// <typeparam name="T"></typeparam>
        ///// <param name="id"></param>
        //public static void Delete<T>(ObjectId id) where T : class, new()
        //{
        //    var col = GetCollection<T>();
        //    IMongoQuery query = Query.EQ("_id", id);
        //    col.Remove(query);
        //}
        #endregion
    }
}
View Code

service:

Core3.1WebApi使用MongoDB
using System.Threading.Tasks;
using ZRF.Models;

namespace ZRF.Service
{
    using System.Collections.Generic;
    using ZRF.IContract;
    using ZRF.MyMongoDB;
    using System.Linq.Expressions;
    using System;
    using MongoDB.Driver;
    using MongoDB.Driver.Linq;
    using MongoDB.Bson;
    using MongoDB.Driver.Builders;
    using System.Linq;

    public class mongoService<T> : ImongoContract<T> where T : class, new()
    {
        #region mongodb数据库的链接操作配置

        //只是简单的来测试一下,先不放在配置里面了
        private static readonly string connectionStr = "mongodb://zrf_fengge:FEG_ZRF@47.107.87.32:27017/zrfmongodb";
        private static readonly string dbName = "zrfmongodb";
        public IMongoCollection<T> GetCollection()
        {
            IMongoClient client = new MongoClient(connectionStr);
            return client.GetDatabase(dbName).GetCollection<T>(typeof(T).Name);
        }

        /// <summary>
        /// 自定义 链接mongodb数据库字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dbname"></param>
        /// <param name="connectionStr"></param>
        /// <returns></returns>
        public IMongoCollection<T> GetCollection(string dbname, string myconnectionStr = "")
        {
            IMongoClient client;
            if (myconnectionStr == "")
            {
                client = new MongoClient(myconnectionStr);
            }
            else
            {
                client = new MongoClient(connectionStr);
            }
            return client.GetDatabase(dbname).GetCollection<T>(typeof(T).Name);
        }
        #endregion

        #region 新增操作
        public bool InsertOne(T entity)
        {
            try
            {
                GetCollection().InsertOne(entity);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        public async Task<bool> InsertOneAsync(T entity)
        {
            try
            {
                await GetCollection().InsertOneAsync(entity);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        public bool InsertMany(IEnumerable<T> entity)
        {
            try
            {
                GetCollection().InsertMany(entity);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        public async Task<bool> InsertManyAsync(IEnumerable<T> entity)
        {
            try
            {
                await GetCollection().InsertManyAsync(entity);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        #endregion

        #region 查询
        public T FindOneByFunc(Expression<Func<T, bool>> func)
        {
            FilterDefinition<T> filter = new FilterDefinitionBuilder<T>().Where(func);
            var find = GetCollection().Find<T>(filter);
            return find.FirstOrDefault();
        }
        public async Task<T> FindOneByFuncAsync(Expression<Func<T, bool>> func)
        {
            FilterDefinition<T> filter = new FilterDefinitionBuilder<T>().Where(func);
            var find = await GetCollection().FindAsync<T>(filter);
            return find.FirstOrDefault();
        }
        public IEnumerable<T> FindList(Expression<Func<T, bool>> func)
        {
            FilterDefinition<T> filter = new FilterDefinitionBuilder<T>().Where(func);
            var find = GetCollection().Find<T>(filter);
            return find.ToList();
        }
        public async Task<IEnumerable<T>> FindListAsync(Expression<Func<T, bool>> func)
        {
            FilterDefinition<T> filter = new FilterDefinitionBuilder<T>().Where(func);
            var find = await GetCollection().FindAsync<T>(filter);
            return find.ToList();
        }


        public async Task<PageData> FindListByPagenationwithOrderAsyn(Expression<Func<T, bool>> where, bool orderAscTrue, Expression<Func<T, object>> OrderBy, int pageIndex = 1, int pageSize = 20)
        {
            PageData pd = new PageData();
            await Task.Factory.StartNew(() =>
            {
                pd.pageSize = pageSize;
                pd.index = pageIndex;
                int skip = (pageIndex - 1) * pageSize;
                int limit = pageSize;
                IMongoQueryable<T> queable = GetCollection().AsQueryable();
                if (where != null)
                {
                    queable = queable.Where(where);
                }
                if (orderAscTrue)
                {
                    queable = queable.OrderBy(OrderBy);
                }
                else
                {
                    queable = queable.OrderByDescending(OrderBy);
                }
                pd.totalRows = queable.Count();
                pd.data = queable.Skip(skip).Take(limit).ToList();
            });
            return pd;
        }
        public async Task<PageData> FindListByPagenationAsyn(Expression<Func<T, bool>> where, int pageIndex, int pageSize)
        {
            PageData pd = new PageData();
            await Task.Factory.StartNew(() =>
            {
                pd.pageSize = pageSize;
                pd.index = pageIndex;
                int skip = (pageIndex - 1) * pageSize;
                int limit = pageSize;
                IMongoQueryable<T> queable = GetCollection().AsQueryable();
                if (where != null)
                {
                    queable = queable.Where(where);
                }
                pd.totalRows = queable.Count();
                pd.data = queable.Skip(skip).Take(limit).ToList();
            });
            return pd;
        }

        /// <summary>
        /// 根据条件查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dics"></param>
        /// <returns></returns>
        public async Task<List<T>> QueryList(Dictionary<string, object> dics)
        {
            var collection = GetCollection();
            var query = new QueryDocument(dics);
            var result = await collection.FindAsync<T>(query);
            return result.ToList<T>();
        }

        #endregion

        #region 修改
        /// <summary>
        /// 编辑
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="id"></param>
        public void Update(T entity, ObjectId id)
        {
            var collection = GetCollection();
            BsonDocument bsd = BsonExtensionMethods.ToBsonDocument(entity);
            IMongoQuery query = Query.EQ("_id", id);
            var filter = query.ToBsonDocument();
            collection.UpdateOne(filter, new UpdateDocument(bsd));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public bool Update(T entity)
        {
            var query = new QueryDocument { { "myid", "F110" } };
            var updateObj = new UpdateDocument { { "$set", new QueryDocument { { "name", "小张" } } } };

            UpdateResult updateResult = GetCollection().UpdateOne(query, updateObj);
            return updateResult.ModifiedCount > 0;
        }

        #endregion

        #region 删除,备份
        ///// <summary>
        ///// 删除
        ///// remark:条件删除
        ///// </summary>
        ///// <typeparam name="T"></typeparam>
        ///// <param name="dics"></param>
        //public static void Delete<T>(Dictionary<string, object> dics) where T : class, new()
        //{
        //    var col = GetCollection<T>();

        //    var query = new QueryDocument(dics);

        //    var result = col.Remove(query);
        //}

        ///// <summary>
        ///// 删除
        ///// remark:根据ObjectId删除
        ///// </summary>
        ///// <typeparam name="T"></typeparam>
        ///// <param name="id"></param>
        //public static void Delete<T>(ObjectId id) where T : class, new()
        //{
        //    var col = GetCollection<T>();
        //    IMongoQuery query = Query.EQ("_id", id);
        //    col.Remove(query);
        //}
        #endregion
    }
}
View Code

WebApi:

Core3.1WebApi使用MongoDB
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ZRFCoreTestMongoDB.Controllers
{
    using ZRFCoreTestMongoDB.Model;
    using Microsoft.AspNetCore.Mvc;
    using ZRF.IContract;
    using ZRF.Models;
    [ApiController]
    [Route("api/[Controller]")]
    public class Test01Controller : ControllerBase
    {
        private ImongoContract<studentInfo> _server;

        public Test01Controller(ImongoContract<studentInfo> server)
        {
            _server = server;
        }

        /// <summary>
        /// 批量写入的操作
        /// </summary>
        /// <returns></returns>

        [HttpGet, Route("doinsert")]
        public async Task<ApiResult> DoInsert()
        {
            ApiResult result = new ApiResult();
            try
            {
                string[] colorArry = new string[] { "red", "blue", "orager" };
                List<studentInfo> studentList = new List<studentInfo>();
                for (int i = 0; i < 2000000; i++)
                {
                    studentInfo info = new studentInfo
                    {
                        age = new Random().Next(18, 38),
                        birthday = DateTime.Now.AddYears(-(new Random().Next(12, 30))),
                        name = "name" + new Random().Next(1000, 9999),
                        pid = Guid.NewGuid().ToString(),
                        books = new List<book> {
                           new book
                           {
                             authname="小张"+i,
                             bid=Guid.NewGuid().ToString(),
                             bname="bname"+i,
                             saledate=DateTime.Now.AddYears(-(new Random().Next(1,30))),
                             saleprice=new Random().Next(15,125)*1.0f,
                             binfo=new bookpropetity{
                             bcount=new Random().Next(120,350),
                             color=colorArry[new Random().Next(0,3)],
                             heigh=25,
                             width=18
                             }
                           }
                         }
                    };
                    studentList.Add(info);
                    if (studentList.Count >= 2000)
                    {
                        bool flag = await _server.InsertManyAsync(studentList);
                        studentList.Clear();
                    }
                }
                if (studentList.Count > 0)
                {
                    bool flag = await _server.InsertManyAsync(studentList);
                }
                result.code = statuCode.success;
                result.message = "写入成功";
            }
            catch (Exception ex)
            {
                result.message = "写入异常+" + ex.Message;
            }
            return result;
        }

        [HttpGet, Route("DoQueryByPagenation")]
        public async Task<ApiResult> DoQuery(int pageIndex = 1, int pageSize = 20)
        {
            ApiResult result = new ApiResult();
            try
            {
                var pd = await _server.FindListByPagenationAsyn(c => c.books[0].binfo.color=="red", pageIndex, pageSize);
                result.data = pd;
                result.message = "查询成功";
                result.code = statuCode.success;
            }
            catch (Exception ex)
            {
                result.message = "查询异常:" + ex.Message;
            }
            return result;
        }
    }
}
View Code

效果截图:(数据一共批量先写入400百万条,不是太多,写入的速度平均为:12000-15000条的样子,阿里云上面的单核1G最低的那种配置吧)

Core3.1WebApi使用MongoDB

Core3.1WebApi使用MongoDB

 

Core3.1WebApi使用MongoDB

上一篇:MySQL基础_流程控制结构


下一篇:SAP SQL 表inner join 不同长度字段连接