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

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 where T : class, new()
    {
        #region mongodb数据库的链接操作配置
        IMongoCollection GetCollection();
        /// 
        /// 自定义 链接mongodb数据库字符串
        /// 
        /// 
        /// 
        /// 
        /// 
        IMongoCollection GetCollection(string dbname, string myconnectionStr = "");

        #endregion

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

        Task<bool> InsertOneAsync(T entity);

        bool InsertMany(IEnumerable entity);

        Task<bool> InsertManyAsync(IEnumerable entity);

        #endregion

        #region 查询
        T FindOneByFunc(Expressionbool>> func);

        Task FindOneByFuncAsync(Expressionbool>> func);

        IEnumerable FindList(Expressionbool>> func);

        Task> FindListAsync(Expressionbool>> func);

        Task FindListByPagenationwithOrderAsyn(Expressionbool>> where, bool orderAscTrue, Expressionobject>> OrderBy, int pageIndex = 1, int pageSize = 20);
        Task FindListByPagenationAsyn(Expressionbool>> where, int pageIndex, int pageSize);

        /// 
        /// 根据条件查询
        /// 
        /// 
        /// 
        /// 
        Task> QueryList(Dictionary<string, object> dics);


        #endregion

        #region 修改
        /// 
        /// 编辑
        /// 
        /// 
        /// 
        /// 
        void Update(T entity, ObjectId id);

        /// 
        /// 
        /// 
        /// 
        /// 
        bool Update(T entity);

        #endregion

        #region 删除,备份
        ///// 
        ///// 删除
        ///// remark:条件删除
        ///// 
        ///// 
        ///// 
        //public static void Delete(Dictionary dics) where T : class, new()
        //{
        //    var col = GetCollection();

        //    var query = new QueryDocument(dics);

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

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

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 : ImongoContract 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 GetCollection()
 25         {
 26             IMongoClient client = new MongoClient(connectionStr);
 27             return client.GetDatabase(dbName).GetCollection(typeof(T).Name);
 28         }
 29 
 30         /// 
 31         /// 自定义 链接mongodb数据库字符串
 32         /// 
 33         /// 
 34         /// 
 35         /// 
 36         /// 
 37         public IMongoCollection 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(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 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 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(Expressionbool>> func)
105         {
106             FilterDefinition filter = new FilterDefinitionBuilder().Where(func);
107             var find = GetCollection().Find(filter);
108             return find.FirstOrDefault();
109         }
110         public async Task FindOneByFuncAsync(Expressionbool>> func)
111         {
112             FilterDefinition filter = new FilterDefinitionBuilder().Where(func);
113             var find = await GetCollection().FindAsync(filter);
114             return find.FirstOrDefault();
115         }
116         public IEnumerable FindList(Expressionbool>> func)
117         {
118             FilterDefinition filter = new FilterDefinitionBuilder().Where(func);
119             var find = GetCollection().Find(filter);
120             return find.ToList();
121         }
122         public async Task> FindListAsync(Expressionbool>> func)
123         {
124             FilterDefinition filter = new FilterDefinitionBuilder().Where(func);
125             var find = await GetCollection().FindAsync(filter);
126             return find.ToList();
127         }
128 
129 
130         public async Task FindListByPagenationwithOrderAsyn(Expressionbool>> where, bool orderAscTrue, Expressionobject>> 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 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 FindListByPagenationAsyn(Expressionbool>> 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 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         /// 
178         /// 根据条件查询
179         /// 
180         /// 
181         /// 
182         /// 
183         public async Task> QueryList(Dictionary<string, object> dics)
184         {
185             var collection = GetCollection();
186             var query = new QueryDocument(dics);
187             var result = await collection.FindAsync(query);
188             return result.ToList();
189         }
190 
191         #endregion
192 
193         #region 修改
194         /// 
195         /// 编辑
196         /// 
197         /// 
198         /// 
199         /// 
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         /// 
210         /// 
211         /// 
212         /// 
213         /// 
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         ///// 
227         ///// 删除
228         ///// remark:条件删除
229         ///// 
230         ///// 
231         ///// 
232         //public static void Delete(Dictionary dics) where T : class, new()
233         //{
234         //    var col = GetCollection();
235 
236         //    var query = new QueryDocument(dics);
237 
238         //    var result = col.Remove(query);
239         //}
240 
241         ///// 
242         ///// 删除
243         ///// remark:根据ObjectId删除
244         ///// 
245         ///// 
246         ///// 
247         //public static void Delete(ObjectId id) where T : class, new()
248         //{
249         //    var col = GetCollection();
250         //    IMongoQuery query = Query.EQ("_id", id);
251         //    col.Remove(query);
252         //}
253         #endregion
254     }
255 }

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 _server;

        public Test01Controller(ImongoContract server)
        {
            _server = server;
        }

        /// 
        /// 批量写入的操作
        /// 
        /// 

        [HttpGet, Route("doinsert")]
        public async Task DoInsert()
        {
            ApiResult result = new ApiResult();
            try
            {
                string[] colorArry = new string[] { "red", "blue", "orager" };
                List studentList = new List();
                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 {
                           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 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;
        }
    }
}

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

相关