Core3.1WebApi使用MongoDB

好久没有使用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:

复制代码
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:

复制代码
  1 using System.Threading.Tasks;
  2 using ZRF.Models;
  3 
  4 namespace ZRF.Service
  5 {
  6     using System.Collections.Generic;
  7     using ZRF.IContract;
  8     using ZRF.MyMongoDB;
  9     using System.Linq.Expressions;
 10     using System;
 11     using MongoDB.Driver;
 12     using MongoDB.Driver.Linq;
 13     using MongoDB.Bson;
 14     using MongoDB.Driver.Builders;
 15     using System.Linq;
 16 
 17     public class mongoService<T> : ImongoContract<T> where T : class, new()
 18     {
 19         #region mongodb数据库的链接操作配置
 20 
 21         //只是简单的来测试一下,先不放在配置里面了
 22         private static readonly string connectionStr = "mongodb://zrf_fengge:FEG_ZRF@47.217.66.39:27017/zrfmongodb";
 23         private static readonly string dbName = "zrfmongodb";
 24         public IMongoCollection<T> GetCollection()
 25         {
 26             IMongoClient client = new MongoClient(connectionStr);
 27             return client.GetDatabase(dbName).GetCollection<T>(typeof(T).Name);
 28         }
 29 
 30         /// <summary>
 31         /// 自定义 链接mongodb数据库字符串
 32         /// </summary>
 33         /// <typeparam name="T"></typeparam>
 34         /// <param name="dbname"></param>
 35         /// <param name="connectionStr"></param>
 36         /// <returns></returns>
 37         public IMongoCollection<T> GetCollection(string dbname, string myconnectionStr = "")
 38         {
 39             IMongoClient client;
 40             if (myconnectionStr == "")
 41             {
 42                 client = new MongoClient(myconnectionStr);
 43             }
 44             else
 45             {
 46                 client = new MongoClient(connectionStr);
 47             }
 48             return client.GetDatabase(dbname).GetCollection<T>(typeof(T).Name);
 49         }
 50         #endregion
 51 
 52         #region 新增操作
 53         public bool InsertOne(T entity)
 54         {
 55             try
 56             {
 57                 GetCollection().InsertOne(entity);
 58                 return true;
 59             }
 60             catch (Exception)
 61             {
 62                 return false;
 63             }
 64         }
 65         public async Task<bool> InsertOneAsync(T entity)
 66         {
 67             try
 68             {
 69                 await GetCollection().InsertOneAsync(entity);
 70                 return true;
 71             }
 72             catch (Exception)
 73             {
 74                 return false;
 75             }
 76         }
 77         public bool InsertMany(IEnumerable<T> entity)
 78         {
 79             try
 80             {
 81                 GetCollection().InsertMany(entity);
 82                 return true;
 83             }
 84             catch (Exception)
 85             {
 86                 return false;
 87             }
 88         }
 89         public async Task<bool> InsertManyAsync(IEnumerable<T> entity)
 90         {
 91             try
 92             {
 93                 await GetCollection().InsertManyAsync(entity);
 94                 return true;
 95             }
 96             catch (Exception)
 97             {
 98                 return false;
 99             }
100         }
101         #endregion
102 
103         #region 查询
104         public T FindOneByFunc(Expression<Func<T, bool>> func)
105         {
106             FilterDefinition<T> filter = new FilterDefinitionBuilder<T>().Where(func);
107             var find = GetCollection().Find<T>(filter);
108             return find.FirstOrDefault();
109         }
110         public async Task<T> FindOneByFuncAsync(Expression<Func<T, bool>> func)
111         {
112             FilterDefinition<T> filter = new FilterDefinitionBuilder<T>().Where(func);
113             var find = await GetCollection().FindAsync<T>(filter);
114             return find.FirstOrDefault();
115         }
116         public IEnumerable<T> FindList(Expression<Func<T, bool>> func)
117         {
118             FilterDefinition<T> filter = new FilterDefinitionBuilder<T>().Where(func);
119             var find = GetCollection().Find<T>(filter);
120             return find.ToList();
121         }
122         public async Task<IEnumerable<T>> FindListAsync(Expression<Func<T, bool>> func)
123         {
124             FilterDefinition<T> filter = new FilterDefinitionBuilder<T>().Where(func);
125             var find = await GetCollection().FindAsync<T>(filter);
126             return find.ToList();
127         }
128 
129 
130         public async Task<PageData> FindListByPagenationwithOrderAsyn(Expression<Func<T, bool>> where, bool orderAscTrue, Expression<Func<T, object>> OrderBy, int pageIndex = 1, int pageSize = 20)
131         {
132             PageData pd = new PageData();
133             await Task.Factory.StartNew(() =>
134             {
135                 pd.pageSize = pageSize;
136                 pd.index = pageIndex;
137                 int skip = (pageIndex - 1) * pageSize;
138                 int limit = pageSize;
139                 IMongoQueryable<T> queable = GetCollection().AsQueryable();
140                 if (where != null)
141                 {
142                     queable = queable.Where(where);
143                 }
144                 if (orderAscTrue)
145                 {
146                     queable = queable.OrderBy(OrderBy);
147                 }
148                 else
149                 {
150                     queable = queable.OrderByDescending(OrderBy);
151                 }
152                 pd.totalRows = queable.Count();
153                 pd.data = queable.Skip(skip).Take(limit).ToList();
154             });
155             return pd;
156         }
157         public async Task<PageData> FindListByPagenationAsyn(Expression<Func<T, bool>> where, int pageIndex, int pageSize)
158         {
159             PageData pd = new PageData();
160             await Task.Factory.StartNew(() =>
161             {
162                 pd.pageSize = pageSize;
163                 pd.index = pageIndex;
164                 int skip = (pageIndex - 1) * pageSize;
165                 int limit = pageSize;
166                 IMongoQueryable<T> queable = GetCollection().AsQueryable();
167                 if (where != null)
168                 {
169                     queable = queable.Where(where);
170                 }
171                 pd.totalRows = queable.Count();
172                 pd.data = queable.Skip(skip).Take(limit).ToList();
173             });
174             return pd;
175         }
176 
177         /// <summary>
178         /// 根据条件查询
179         /// </summary>
180         /// <typeparam name="T"></typeparam>
181         /// <param name="dics"></param>
182         /// <returns></returns>
183         public async Task<List<T>> QueryList(Dictionary<string, object> dics)
184         {
185             var collection = GetCollection();
186             var query = new QueryDocument(dics);
187             var result = await collection.FindAsync<T>(query);
188             return result.ToList<T>();
189         }
190 
191         #endregion
192 
193         #region 修改
194         /// <summary>
195         /// 编辑
196         /// </summary>
197         /// <typeparam name="T"></typeparam>
198         /// <param name="entity"></param>
199         /// <param name="id"></param>
200         public void Update(T entity, ObjectId id)
201         {
202             var collection = GetCollection();
203             BsonDocument bsd = BsonExtensionMethods.ToBsonDocument(entity);
204             IMongoQuery query = Query.EQ("_id", id);
205             var filter = query.ToBsonDocument();
206             collection.UpdateOne(filter, new UpdateDocument(bsd));
207         }
208 
209         /// <summary>
210         /// 
211         /// </summary>
212         /// <typeparam name="T"></typeparam>
213         /// <returns></returns>
214         public bool Update(T entity)
215         {
216             var query = new QueryDocument { { "myid", "F110" } };
217             var updateObj = new UpdateDocument { { "$set", new QueryDocument { { "name", "小张" } } } };
218 
219             UpdateResult updateResult = GetCollection().UpdateOne(query, updateObj);
220             return updateResult.ModifiedCount > 0;
221         }
222 
223         #endregion
224 
225         #region 删除,备份
226         ///// <summary>
227         ///// 删除
228         ///// remark:条件删除
229         ///// </summary>
230         ///// <typeparam name="T"></typeparam>
231         ///// <param name="dics"></param>
232         //public static void Delete<T>(Dictionary<string, object> dics) where T : class, new()
233         //{
234         //    var col = GetCollection<T>();
235 
236         //    var query = new QueryDocument(dics);
237 
238         //    var result = col.Remove(query);
239         //}
240 
241         ///// <summary>
242         ///// 删除
243         ///// remark:根据ObjectId删除
244         ///// </summary>
245         ///// <typeparam name="T"></typeparam>
246         ///// <param name="id"></param>
247         //public static void Delete<T>(ObjectId id) where T : class, new()
248         //{
249         //    var col = GetCollection<T>();
250         //    IMongoQuery query = Query.EQ("_id", id);
251         //    col.Remove(query);
252         //}
253         #endregion
254     }
255 }
View Code
复制代码

WebApi:

复制代码
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最低的那种配置吧)

 

posted @   天天向上518  阅读(365)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示